C Language Simple Assertion


Example

An assertion is a statement used to assert that a fact must be true when that line of code is reached. Assertions are useful for ensuring that expected conditions are met. When the condition passed to an assertion is true, there is no action. The behavior on false conditions depends on compiler flags. When assertions are enabled, a false input causes an immediate program halt. When they are disabled, no action is taken. It is common practice to enable assertions in internal and debug builds, and disable them in release builds, though assertions are often enabled in release. (Whether termination is better or worse than errors depends on the program.) Assertions should be used only to catch internal programming errors, which usually means being passed bad parameters.

#include <stdio.h>
/* Uncomment to disable `assert()` */
/* #define NDEBUG */
#include <assert.h>

int main(void)
{
    int x = -1;
    assert(x >= 0);

    printf("x = %d\n", x);   
    return 0;
}

Possible output with NDEBUG undefined:

a.out: main.c:9: main: Assertion `x >= 0' failed.

Possible output with NDEBUG defined:

x = -1

It's good practice to define NDEBUG globally, so that you can easily compile your code with all assertions either on or off. An easy way to do this is define NDEBUG as an option to the compiler, or define it in a shared configuration header (e.g. config.h).