assert.h
assert(e) from <assert.h> aborts the program if e is false. It is a debug check, not an error-handling path. Defining NDEBUG before the include turns every assert into a no-op.
Detailed Explanation
assert(p != NULL); documents an invariant: if p is null here, the program is wrong and should die loudly. In a debug build it prints the expression, the file, and the line, then calls abort. In a release build with -DNDEBUG, the expression is not evaluated. Side effects in the expression vanish. assert(i++ < n) is a defect: i does not increment in release.
That is the contract. Assertions catch programmer mistakes — a caller broke the precondition, a slot is empty when the algorithm says it cannot be. They do not catch bad user input. A parser that asserts the file is well-formed will abort in production if you forgot NDEBUG, or silently accept garbage if you remembered it. Return an error.
assert is a macro. Including <assert.h> again after changing NDEBUG can redefine it; that is why some files include it at the bottom of a config header. static_assert (C11, _Static_assert) is a compile-time check and is not affected by NDEBUG. Use it for sizes, enum ranges, and "this struct is 16 bytes."
Writing assert(0 && "unreachable") marks a switch default you believe is dead. In release that default becomes silent fall-through unless you also abort or return. Prefer default: abort(); for truly impossible cases you still want closed in production, or handle the case.
Do not use assert for security checks you need in production. An overflow check that disappears under NDEBUG is an overflow.
Code Examples
#include <assert.h>
#include <stdio.h>
static int at(const int *a, int n, int i)
{
assert(a != NULL);
assert(i >= 0 && i < n);
return a[i];
}
int main(void)
{
int a[] = { 4, 5, 6 };
printf("%d\n", at(a, 3, 1)); /* prints: 5 */
return 0;
}#include <assert.h>
#include <stdio.h>
int main(void)
{
static_assert(sizeof(int) >= 2, "int is at least 16 bits");
printf("ok\n"); /* prints: ok */
return 0;
}Common Gotchas
Putting a needed side effect in `assert` drops it when `NDEBUG` is set
the release build changes behavior, not just checking.
`assert` is not for user-facing errors
a failed parse should return a code, not abort.
`static_assert` is compile-time and always on
use it for ABI and size invariants.
A production `assert` that fires is an `abort`
no stack of `atexit` handlers is required to run; flush what you must before you assert in I/O paths, or do not assert there.