Assertions and unreachable paths

suggest change

Use assert to document an internal invariant that should be true whenever execution reaches a point:

#include <assert.h>
#include <stdlib.h>

enum color { color_red, color_green, color_blue };

void validate_color(enum color color)
{
    switch (color) {
    case color_red:
    case color_green:
    case color_blue:
        break;
    default:
        assert(!"invalid color value");
        abort();
    }
}

When assertions are enabled, a false assertion writes diagnostic information to the standard error stream and calls abort. Defining NDEBUG before including <assert.h> disables the check. The explicit abort above preserves termination when assertions are disabled.

Do not use assert to validate user input, allocation success, file contents, or any condition a correct program can encounter at run time. Those cases need ordinary error handling that remains active in every build.

Whether assertions remain enabled in production is a project policy. They are useful for detecting violated invariants, but abort does not run functions registered with atexit and may be inappropriate for a recoverable condition.

Compiler-specific “unreachable” intrinsics and C23's unreachable macro are optimization promises, not error handling. Reaching a path declared unreachable causes undefined behavior, so use such a promise only when the condition is already guaranteed by the program's logic.

Feedback about page:

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



Table Of Contents