The C++ standard library's
is a header file in the C++ standard library that provides an assertion feature for checking at runtime whether a condition is true. If the condition is false, the program terminates and outputs an error message. Assertions are mainly used during debugging to ensure the logical correctness of the program.
An assertion is a debugging tool used to check the program's running state during development. If an assertion fails, the program terminates immediately, which helps developers quickly locate the problem.
Syntax
cassert The assert macro's basic syntax is as follows:
#include
assert(expression);
where expression is a Boolean expression; if the result of the expression is true, the program continues; if the result is false, the program terminates and outputs an error message.
Example
Below is an example using cassert A simple example of :
Example
#include
#include
int
main
(
)
{
int
a
=
5
;
int
b
=
3
;
// Check whether a is greater than b
assert
(
a
b
)
;
// If a is not greater than b, the program will terminate here and output an error message
std
::
cout
<<
"a is greater than b"
<<
std
::
endl
;
return
0
;
}
Output result
When running the program above, since a is indeed greater than b, the program executes normally and outputs:
a is greater than b
If we change a 's value to 2, making it not greater than b, the program will output an error message and terminate:
Assertion failed: a > b, file main.cpp, line 8.
Advanced usage of assertions
assert macro can also accept an additional expression to output a custom error message:
Example
#include
#include
int
main
(
)
{
int
x
=
10
;
int
y
=
0
;
// Using a custom error message
assert
(
y
!
=
0
&&
"Division by zero error"
)
;
int
result
=
x
/
y
;
// This line of code will not execute because the assertion has already failed
return
0
;
}
When running the program above, since y is 0, the assertion will fail and output:
Division by zero error
Assertion failed: y != 0 && "Division by zero error", file main.cpp, line 8.
Notes
-
In release builds, assertions usually need to be disabled to avoid unexpected termination at runtime. This can be done by defining
NDEBUGmacro:
#define NDEBUG #include
-
Assertions should only be used to check for logical errors in the program, not for handling runtime errors. Runtime errors should be handled through exception handling or other mechanisms.
-
Assertion expressions should be simple, avoiding complex logic or computation to reduce performance overhead.
By using cassert The assert macro, developers can quickly discover and fix logical errors during development, improving the program's stability and reliability.