assert(condition) from <assert.h> aborts the program with a message showing the file, line, and condition if the condition is false. Use it for conditions that must always be true (bugs), not for user input errors. Defining NDEBUG removes all asserts, so never put required side effects inside them.
Remember
#include <assert.h>
assert(ptr != NULL);
assert(index >= 0 && index < size);
/* gcc -DNDEBUG disables every assert */
Reference
Cheat Sheet
Keep these facts handy while you work with Assertions in C.
Topic
Detail
Fails
Prints location and calls abort()
Disable
-DNDEBUG
Use for
Internal invariants
Not for
Input validation
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: static_assert.
Example 1 — Guard a precondition
The assertion documents that n must be positive.
C
#include <assert.h>
#include <stdio.h>
static double average(const int *a, int n) {
assert(a != NULL);
assert(n > 0);
int sum = 0;
for (int i = 0; i < n; i++) sum += a[i];
return (double)sum / n;
}
int main(void) {
int v[] = {1, 2, 3, 4};
printf("average = %.1f\n", average(v, 4));
return 0;
}
Output
average = 2.5
How It Works
Both assertions pass for valid input.
Calling average(v, 0) would print Assertion failed: n > 0 with the file and line, then abort.
The cast to double keeps the fractional average, 10 / 4 = 2.5.
Edge Cases & Pitfalls
Check these before relying on Assertions in real programs.
side
Side effects inside assert
assert(i++ < 10) loses the increment when NDEBUG is set.
input
Validating user input with assert
Release builds remove asserts, so real input errors must use normal error handling.
Remember
Key Takeaways
Invariants: assert them.
Input: handle errors properly.
NDEBUG: removes asserts.
One line: assert(condition) from <assert.h> aborts the program with a message showing the file, line, and condition if the condition is false.
Frequently Asked Questions
The program prints a diagnostic with the expression, file, and line number to stderr and calls abort().
Many projects disable them with NDEBUG for speed; others keep them for safety. Never rely on them for input validation.
Continue with "C static_assert" next. Check conditions at compile time with static_assert (C11). The C Advanced Concepts hub lists every topic in order.