The <assert.h> header is part of the standard library of the C programming language that provides two macros that implement an assertion - a way to verify that some assumption made by the code is true. If the assumption was false, a diagnostic message gets printed. The header provides both a run-time assertion and a compile-time assertion.
The macros evaluates an expression. When the expression is false, I.E. compares to 0, the assert macro writes information about the particular call that failed on to the standard error file.
Debug mode
The header depends on another macro NDEBUG which is not defined by <assert.h> itself. If NDEBUG is defined as a macro name at the point in the source file where <assert.h> is included, the assert macro behave as if they were noops - with absolutely no effect on the program.
#define NDEBUG
#include <assert.h>
/* assertions have no effect on the program */
Macros
The header provides two macro definitions:
Macro Name | Description | Since |
---|---|---|
assert | implements a run-time assertion | C89 |
static_assert | implements a compile-time assertion | C11 |
Diagnostic message
An example of the diagnostic message as a result of the Template:Assert.h/assert macro is:
Assertion failed: data != NULL, function load_data, file foo.c, line 94.
Run-time assertion
Run-time assertion refers to the ability to assert a certain condition during the execution of the program. The assert macro provides such facilities. Checking the certain conditions are true during the execution of a program is crucial for validating that an algorithm is performing correctly.
Compile-time assertion
Compile-time assertion refers to the ability to assert a certain condition during the compilation stage, provided the condition evaluates to a compile-time constant. The static_assert macro provides the facilities for a compile-time assertion.