Assert.h


assert.h is a header file in the standard library of the C programming language that defines the C preprocessor macro assert.
In C++ it is also available through the <cassert> header file.

Assert

assert;
This is a macro that implements a runtime assertion, which can be used to verify assumptions made by the program and print a diagnostic message if this assumption is false.
When executed, if the expression is false, assert will write information about the call that failed on stderr and then call abort. The information it writes to stderr includes:
Example output of a program compiled on Linux:
program: program.c:5: main: Assertion `a != 1' failed.
Abort
Programmers can eliminate the assertions just by recompiling the program, without changing the source code: if the macro NDEBUG is defined before the inclusion of , the assert macro may be defined simply as:
#define assert
and therefore has no effect on the compilation unit, not even evaluating its argument. Therefore expressions passed to assert must not contain side-effects since they will not happen when debugging is disabled. For instance:
assert);
will not read a line and not assign to x when debugging is disabled.

Additional message

Although Microsoft has its own "assert with message" macro, there is no standardized variant of assert that includes an error message. This can nevertheless be achieved using a comma operator, which discards all preceding values and only keep the last one:

assert);
// or
  1. define assertmsg assert)
assertmsg;

Will yield something similar to:
program: program.c:5: main: Assertion `' failed.
Abort

Static assert


static_assert;

C++11 added a similar keyword static_assert that contextually converts a constant expression to bool and prints a message at compile-time if it is false. It is possible to simulate this using a macro and templates, though this is probably not necessary since most modern C++ compilers support this C++11 feature.
This feature was formally added in C11 as the keyword _Static_assert with an identical usage, and in a convenience macro static_assert is added.
It is possible to simulate a static assertion in older versions of C using a macro: #define static_assert char _temp, though the resulting error is cryptic. Gnulib's version of the static assert uses sizeof and a structure to trigger a similar error.

Example


  1. include
  2. include
int test_assert
int main

i = 0
i = 1
i = 2
i = 3
i = 4
assert: assert.c:6: test_assert: Assertion `x <= 4' failed.
Aborted