assert()

Updated: April 19, 2023

Display a diagnostic message and optionally terminate the program

Synopsis:

#include <assert.h>

void assert( int expression );

Arguments:

expression
Zero if you want to terminate the program; a nonzero value if you don't.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The assert() macro displays 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).

You typically use the assert() macro while developing a program, to identify program logic errors. You should choose the expression so that it's true when the program is functioning as intended.

After the program has been debugged, you can use the special “no debug” identifier, NDEBUG, to remove calls to assert() from the program when it's recompiled. If you use the -D option to qcc or a #define directive to define NDEBUG (with any value), the C preprocessor ignores all assert() calls in the program source.

Note: To remove the calls to assert(), you must define NDEBUG in the code before including the <assert.h> header file (i.e., #include <assert.h>).

If you define NDEBUG, the preprocessor also ignores the expression you pass to assert(). For example, if your code includes:

assert((fd = open("filename", O_RDWR)) != -1);

and you define NDEBUG, the preprocessor ignores the entire call to assert(), including the call to open().

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, POSIX 1003.1

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

Caveats:

assert() is a macro.