C Programming/C Reference/assert.h

< C Programming < C Reference

assert.h defines the macro assert(). The macro 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() writes information about the call that failed on stderr and then calls abort(). The information it writes to stderr includes:

Example output of a program compiled with gcc on Linux:

program: program.c:5: main: Assertion `a != 1' failed.
Abort (core dumped)

Programmers can eliminate the assertions without changing the source code: if the macro NDEBUG is defined before the inclusion of <assert.h>, the assert() macro is defined simply as:

#define assert(ignore)((void) 0)

and therefore has no effect on the program, 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(x = gets());

will not read a line and not assign to x when debugging is disabled.

Macros

Functions

The C99 standard requires no functions to be declared in the assert.h header.

Notes

The definition of the assert macro depends on the state of a macro, NDEBUG, which is not defined in the assert.h header. The macro NDEBUG denotes not using debugging information. If NDEBUG is defined, then assert is defined as an expression which does nothing. Otherwise assert will print debugging information if the expression it tests is false.

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.