Table of contents
1. What is assert.h in C?2. How does assert work?
3. When to use assert.h?
4. Enabling and disabling assert.h
5. Things to keep in mind
6. Common mistakes while using assert.h
assert.h in C?
The header assert.h declares the assert macro, which checks
a given expression at runtime. If the expression evaluates to zero (i.e., it’s false),
the program writes an error message to the standard error stream (stderr)
and then calls abort() to terminate the process immediately.
The error message typically contains:
assert work?
When you include assert.h and use assert(condition) in your code,
the compiler inserts runtime checks. If condition is false, an error message
is printed, and abort() is called, stopping the program. If condition
is true, nothing happens and the program proceeds normally.
// Example: Basic usage of assert
#include <stdio.h>
#include <assert.h>
int main(void) {
int x = 5;
assert(x == 5); // passes, nothing happens
assert(x > 10); // fails, program will abort with an error message
printf("This line won't be reached if the second assert fails.\n");
return 0;
}Assertion failed: (x > 10), file main.c, line 9, followed by program termination.
assert.h?
The primary purpose of assert is to catch programming errors, unexpected
states, or logical inconsistencies during development. Common use cases include:
Typically, assert is not used for user input validation
or production error handling. That’s because assert aborts the
program instead of handling the error gracefully. For user-facing scenarios, you’d usually
code explicit checks and return error codes or handle them with structured error mechanisms.
assert.h
In many development workflows, assert statements are enabled for debugging
builds but disabled in production or release builds. This behavior is controlled by
defining or not defining the NDEBUG macro (No Debug).
If NDEBUG is defined before #include <assert.h>,
then all assert calls become no-ops (no operation) — they are effectively
removed from the compiled program.
// Example: disabling asserts
#define NDEBUG
#include <assert.h>
int main(void) {
int y = 0;
assert(y != 0); // This does nothing because NDEBUG is defined
// Program won't abort, even if y == 0
return 0;
}-DNDEBUG to your compiler
(e.g. gcc) to define NDEBUG and thus disable asserts
in a release build.
assert is extremely helpful
during debugging because it immediately flags unexpected conditions.
assert everywhere, you might be
testing normal scenarios that should be handled gracefully instead. Reserve it for
truly unexpected “should never happen” conditions.
// Good usage example
#include <assert.h>
// We expect 'index' to never be negative at this point.
void process_element(int index) {
assert(index >= 0);
// ...
}
NDEBUG defined, those checks disappear, so never rely on them for real
error handling.
NDEBUG is defined, that code won’t even run.
Author
Dr. Roger Ianjamasimanana