Previous Page
Next Page

assert

Tests an expression

#include <assert.h>
void assert ( int expression  );

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.

See Also

exit( ), _Exit( ), raise( ), abort( )


Previous Page
Next Page