Learn C
#include "stdlib/assert.h"

Assertions with assert & _Static_assert in C

#concept

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.

#how it works
1

Assert invariants

assert(index < len); before indexing states the contract β€” violations abort immediately with location attached.

2

NDEBUG removes them

Compiling with -DNDEBUG strips all asserts for zero release overhead β€” which is why asserts must never carry side effects.

3

Static asserts check builds

_Static_assert(sizeof(void*) == 8, "64-bit only"); rejects wrong platforms at compile time with your message.

4

Asserts aren't errors

User input, I/O failures, and network faults need handling, not aborting β€” asserts cover programmer-logic invariants only.

#example
#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;
}
Output
5
1The assert states half's contract: even inputs only β€” 10 satisfies it, so execution continues.
2An odd argument would abort here with file, line, and the expression n % 2 == 0 echoed.
35 prints β€” the invariant held and the contract documented itself.
#use cases
Precondition checks (non-NULL, in-range) at function entries
Postcondition and invariant documentation that executes
Compile-time platform assumptions via _Static_assert
Keeping asserts side-effect-free so NDEBUG builds stay correct

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself β€” building beats watching.