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.
Get C in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.