Site Tools


wiki:h-assert

Table of Contents

<assert.h>

<assert.h> provides the assert macro for runtime checking during development. It evaluates a condition and terminates the program with a diagnostic message showing the file, line, and failed condition if it's false.

Assertions are stripped entirely when compiled with -DNDEBUG, so they cost nothing in release builds. Never put side effects in assertions—they won't execute in production.

Example

This example uses assertions to check preconditions, which can be completely removed in release builds.

// compile: gcc -o assertexample assertexample.c
// run: ./assertexample
// description: assertions fire on invalid input; -DNDEBUG disables them entirely
 
#include <assert.h>
#include <stdio.h>
 
int divide(int a, int b) {
    assert(b != 0);
    return a / b;
}
 
int main() {
    printf("%d\n", divide(10, 2));
    printf("%d\n", divide(10, 0));  // assertion fires
    return 0;
}
wiki/h-assert.md · Last modified: by 127.0.0.1