[Previous]
[Contents]
[Next]

assert()

print a diagnostic message and optionally terminates the program

Synopsis:

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

Description:

The assert() macro prints a diagnostic message on the stderr stream, and terminates the program if expression is false (0). The diagnostic message has the form:

Assertion failed: expression, file filename, line linenumber

where

filename
is the name of the source file (the value of the preprocessing macro __FILE__)
linenumber
is the line number of the assertion that failed in the source file (the value of the preprocessing macro __LINE__)

No action is taken if expression is true (nonzero).

The assert() macro is typically used during program development to identify program logic errors. The given expression should be chosen so that it is true when the program is functioning as intended.

After the program has been debugged, the special "no debug" identifier NDEBUG can be used to remove assert() calls from the program when it is re-compiled. If NDEBUG is defined (with any value) with a -d command line option or with a #define directive, the C preprocessor ignores all assert() calls in the program source.

Examples:

#include <stdio.h>
#include <assert.h>

void process_string( char *string )
  {
    /* use assert to check argument */
    assert( string != NULL );
    assert( *string != '\0' );
    /* rest of code follows here */
  }

void main()
  {
    process_string( "hello" );
    process_string( "" );
  }

Classification:

ANSI

Safety:
Interrupt handler No
Signal handler No
Thread Yes

Caveats:

assert() is a macro.


[Previous]
[Contents]
[Next]