Assertions

suggest change

An assertion states a condition that must hold at a particular point in a program. Runtime assertions help detect violated internal assumptions during execution; static assertions reject a translation when a compile-time condition is false.

Runtime Assertions

The assert macro is declared in <assert.h>:

#include <assert.h>

double reciprocal(double value)
{
    assert(value != 0.0);
    return 1.0 / value;
}

If the expression compares unequal to zero, execution continues. Otherwise, assert writes diagnostic information and calls abort.

If NDEBUG is defined when <assert.h> is included, calls to assert are disabled and their expressions are not evaluated. Do not put required validation or side effects inside an assertion:

assert(index++ < count); /* Wrong: index may not be incremented. */

Assertions are best suited to programmer errors and internal invariants. Validate expected runtime failures—such as invalid user input, unavailable files, and allocation failures—with ordinary control flow so the program can report or recover from them.

Static Assertions

A static assertion is checked during translation, and its controlling expression must be an integer constant expression:

static_assert(sizeof(unsigned char) == 1);

In C23, static_assert is a keyword and its message is optional. In C11 and C17, _Static_assert is the language construct and requires a message:

_Static_assert(sizeof(int) >= 2, "int is unexpectedly small");

In those earlier standards, including <assert.h> also provides static_assert as a convenience macro. NDEBUG does not disable static assertions.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents