<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.
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; }
Runtime assertions:
assert(condition): if condition is false, print diagnostic and abort:Assertion failed: (condition), file filename, line NDisabling assertions:
NDEBUG: preprocessor symbol; define before including <assert.h> to disable all assertions-DNDEBUG to remove assertionsUsage patterns:
assert(i++ < 10): the increment won't happen in release)