From WikiChip
assert macro - <assert.h> - C
< c‎ | assert.h

The assert macro, which is part of <assert.h> can be used to insert diagnostic tests into a program.

Synopsis[edit]

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

Description[edit]

When executed, if the expression is false (I.E. compares to zero), a diagnostic message is printed in an implementation-defined format to the standard error stream. Assert then calls the abort function.

The diagnostic message includes:

  • The text of the argument
  • The name of the source file (__FILE__)
  • The source line number (__LINE__)
  • The name of the enclosing function (__func__) (C99)

If NDEBUG is defined as a macro name prior to the inclusion of <assert.h>, assert gets defined as:

#define assert(ignore) ((void)0)

Parameters[edit]

Parameter Description
expression The expression to be evaluated

Returns[edit]

The assert macro returns no value.

Example[edit]

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

int main(void)
{
    int i;

    for (i = 0; i < 10; i++)
    {
        printf("i = %d\n", i);
        assert(i < 5);
    }

    return 0;
}

Example Output:

i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
example: example.c:11: main: Assertion `i < 5' failed.
Aborted (core dumped)

Starting at variable i being set to zero, the loop continues until the assertion fails when i reaches 5. The program terminates by calling abort() after printing the diagnostic message.

See also[edit]