<assert.h> is a C standard header that defines the assert macro. Use it to check assumptions during development. If the expression is false (zero), the program prints a diagnostic to stderr and calls abort().
Remember
#include <assert.h>
assert(expression); // must be true (non-zero)
true → continue
false → message + abort()
NDEBUG defined → assert becomes a no-op
side effects inside assert → avoid (may vanish)
Include the header, write a clear condition, and keep release builds free of side effects.
Add #include <assert.h> at the top of the file.
Write assert(condition) for an internal invariant (non-null pointer, valid index, precondition).
Compile debug builds withoutNDEBUG so failures show file and line.
For release, compile with -DNDEBUG so asserts compile out.
Piece
Required?
Role
#include <assert.h>
Yes
Provides the assert macro
Expression
Yes
Must be non-zero when the program is correct
NDEBUG
No
Define in release to remove all asserts
Pseudocode
Pseudocode
if NDEBUG is defined:
assert(expr) → do nothing
else:
if evaluate(expr) is false (zero):
print diagnostic to stderr // file, line, expr
abort() // program ends
else:
continue
Reference
Cheat Sheet
Keep these facts handy while writing debug checks.
Topic
Detail
Type
Macro in <assert.h> (not a function)
Syntax
assert(expression);
Pass
Expression non-zero → no effect
Fail
Message to stderr + abort()
Release
gcc -DNDEBUG ... strips asserts
Common checks
ptr != NULL, n >= 0, i < len
Compile-time cousin
static_assert (C11 keyword, not this header)
Try it
Live Preview
Simulate what assert does: pick a condition and see pass (continue) or fail (diagnostic + abort).
Browser simulation of assert behavior (same idea as the C examples below).
Result
assert(number >= 0); // number = 25
→ true (non-zero)
→ continue (no abort)
sqrt(25) = 5.00
Trace
Worked Walkthrough — Guard sqrt
A helper must reject negative input before calling sqrt. Trace one success and one failure.
Calculation
Function:
calculate_sqrt(number):
assert(number >= 0)
return sqrt(number)
Call 1: calculate_sqrt(25.0)
number >= 0 → 25 >= 0 → true
assert passes → sqrt(25) → 5.0
Call 2: calculate_sqrt(-4.0)
number >= 0 → -4 >= 0 → false
assert fails → print diagnostic → abort()
sqrt is never called ✓
Code
C Examples
Compile without NDEBUG to see assertions fire: gcc file.c -std=c11 -g -o out. Link math examples with -lm if needed.
Example 1 — Assert Non-Negative Input for sqrt()
Guard a function precondition: the argument to sqrt must not be negative.
Check before use.assert(text != NULL) states the contract of print_first.
Valid call."hello" is non-null → print the first character h.
NULL call. The assertion fails with file and line instead of undefined behavior from text[0].
Debug-only safety. In release with NDEBUG, this check is removed—so never treat assert as your only production guard for untrusted pointers.
Example 3 — assert vs Proper Error Handling
Use return codes for bad user input. Reserve assert for internal guarantees after you already validated the value.
C
#include <assert.h>
#include <stdio.h>
int parse_positive(int n) {
if (n <= 0) {
return -1; /* user error — recoverable */
}
assert(n > 0); /* internal invariant */
return n * 2;
}
int main(void) {
printf("parse_positive(5) = %d\n", parse_positive(5));
printf("parse_positive(-1) = %d\n", parse_positive(-1));
return 0;
}
Output
parse_positive(5) = 10
parse_positive(-1) = -1
How It Works
Handle bad input first.n <= 0 returns -1 without crashing—good for callers and users.
Assert the invariant. After the if, n must be positive; assert documents that for debug builds.
Success path.parse_positive(5) returns 10.
Error path stays calm.parse_positive(-1) returns -1. Pair this style with errno when wrapping library calls.
Edge Cases & Pitfalls
Check these before relying on assert in real projects.
side effects
Never put side effects in assert
Avoid assert(i++) or assignments inside the expression. With NDEBUG, that code may never run.
users
Not for user input
Bad form data or missing files need return codes or messages—not abort().
release
NDEBUG removes all checks
Production builds often define NDEBUG. Do not rely on assert for security or production validation.
static
Do not confuse with static_assert
static_assert is a C11 compile-time check. Runtime assert lives in this header and fails at run time.
Analysis
Performance Notes
Approach
Cost
Best for
Debug assert
One branch (+ string data) per site
Development and tests
Release -DNDEBUG
Zero (compiled out)
Production binaries
Asserts in hot loops
Can slow debug builds
Prefer entry/exit checks
Assertions are cheap compared with I/O. Keep them at function boundaries in debug builds, and strip them with NDEBUG for release.
Remember
Key Takeaways
Role: debug macro that aborts when an assumption fails.
Release: compile with -DNDEBUG to remove asserts.
Safety: no side effects inside assert(...).
Users: validate input with return codes—not assert.
One line:assert documents “this must be true if my code is correct”—loud in debug, gone in release.
Frequently Asked Questions
assert.h is a standard header that defines the assert macro. assert(expression) checks that expression is true during development. If it is false (zero), the program prints a diagnostic to stderr and calls abort().
assert is a macro, not a function. It expands to code that may include __FILE__ and __LINE__. Do not put side effects inside assert—when NDEBUG is defined, that code may disappear.
Define NDEBUG before including assert.h, or compile with -DNDEBUG. When NDEBUG is defined, assert(expression) expands to a no-op and is removed from the binary.
No. assert is for programmer mistakes and internal invariants. User-facing errors need return codes, errno, or messages—not abort(). Users should never crash your app because of assert.
The implementation writes a diagnostic (expression, file, line) to stderr, then calls abort(). The program ends immediately with no recovery path.
assert checks a runtime expression. static_assert (C11) checks a compile-time condition and fails the build if false. Use static_assert for sizes and constants; use assert for runtime assumptions.