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.
Contents
Assert
assert(a != 1);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 (that is, compares equal to 0), assert()
will write information about the call that failed on stderr
and then call abort()
. The information it writes to stderr
includes:
__FILE__
)__LINE__
)__func__
) (added in C99)Example output of a program compiled on Linux:
program: program.c:5: main: Assertion `a != 1' failed. Abort (core dumped)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 <assert.h>
, the assert()
macro may be defined simply as:
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:
will not read a line and not assign to x when debugging is disabled.
Static Assert
static_assert(sizeof(int)>20, "I need huge integers");C++11 added a similar macro static_assert
that computes the value and prints a message at compile-time if it is false. It is possible to simulate this using a macro and templates, though most modern C++ compilers include built-in support (and they might not require the header file).
It is impossible to simulate a static assertion in C using a macro. Instead a keyword _Static_assert
was added to C11 and compilers are expected to implement this.