Name
assert
Synopsis
Tests an expression
#include <assert.h> voidassert( intexpression);
The assert() macro
evaluates a given expression and aborts the program if the result is
0 (that is, false). In this case,
assert() also prints a message on
stderr, indicating the name of
the program, and the source file, line number, and function in which
the failing assert() call
occurs:
program:file:line:function: Assertion 'expression' failed.
If the value of expression is
true (that is, nonzero), assert() does nothing and the program
continues.
Use assert() during
development to guard against logical errors in your program. When
debugging is complete, you can instruct the preprocessor to suppress
all assert() calls by defining
the symbolic constant NDEBUG.
Example
int units_in_stock = 10; int units_shipped = 9; /* ... */ units_shipped++; units_in_stock--; /* ... */ units_in_stock -= units_shipped; assert(units_in_stock >= 0);
This code produces the following output:
inventory: inventory.c:110: main: Assertion `units_in_stock >= 0' failed. Aborted.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access