Assertions with assert & _Static_assert in C
assert() from <assert.h> states what must be true: assert(ptr != NULL); aborts with file, line, and the failed expression when violated in debug builds, and compiles to nothing under -DNDEBUG for release. Assertions document invariants and catch logic errors at the earliest moment β they are executable specifications, not error handling (never assert on user input or runtime conditions).
_Static_assert (C11, static_assert in C23) checks at compile time: _Static_assert(sizeof(int) >= 4, "need 32-bit int"); fails the build, not the run. Use static asserts for assumptions, runtime asserts for invariants, and real error handling for everything else.
Assert invariants
assert(index < len); before indexing states the contract β violations abort immediately with location attached.
NDEBUG removes them
Compiling with -DNDEBUG strips all asserts for zero release overhead β which is why asserts must never carry side effects.
Static asserts check builds
_Static_assert(sizeof(void*) == 8, "64-bit only"); rejects wrong platforms at compile time with your message.
Asserts aren't errors
User input, I/O failures, and network faults need handling, not aborting β asserts cover programmer-logic invariants only.
#include <stdio.h>#include <assert.h>Β int half(int n) { assert(n % 2 == 0); return n / 2;}Β int main(void) { printf("%d\n", half(10)); return 0;}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself β building beats watching.