[Previous] [Contents] [Next]

assert()

Print a diagnostic message and optionally terminate the program

Synopsis:

#include <assert.h>

void assert( int expression );

Library:

libc

Description:

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

The diagnostic message includes the expression, the name of the source file (the value of __FILE__) and the line number of the failed assertion (the value of __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's 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's recompiled. If NDEBUG is defined (with any value) with a -d option to qcc or with a #define directive, the C preprocessor ignores all assert() calls in the program source. NDEBUG must be defined in the code before including the <assert.h> header file (i.e. #include <assert.h>).

Examples:

#include <stdio.h>
#include <stdlib.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 */
}

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

    return EXIT_SUCCESS;
}

Classification:

ANSI

Safety:
Cancellation point No
Interrupt handler No
Signal handler No
Thread Yes

Caveats:

assert() is a macro.

See also:

abort()


[Previous] [Contents] [Next]