Home / Learn Embedded C / Using assert() in Embedded Code
Using assert() in Embedded Code
Catching programmer-error conditions during development, and deciding what to do with asserts in production.
What's actually going on
What it is
assert() checks a condition that should always be true if the program is correct, and (in a typical debug build) halts execution immediately with diagnostic information if it is ever false — a tool for catching programmer logic errors during development, distinct from runtime error handling for expected failure conditions.
Why it matters
assert() is for "this should be logically impossible if my code is correct" conditions (a programmer bug), while the error-handling conventions from the previous lesson are for "this can legitimately fail at runtime" conditions (like invalid user input or a hardware fault) — mixing the two up is a common design mistake.
Mechanically speaking
Many embedded projects disable assert() checks in production release builds (for code size and performance) via the NDEBUG macro — meaning a production build must still handle genuinely possible runtime failures through proper error handling, never relying on an assert() that may not even be compiled in.
Shows up in
- Development-time bug catching
- Debug vs release build strategy
- Code correctness verification
Try it
This models the logic of assert() in plain C, since the real assert() macro is tied to the standard library's NDEBUG behavior.
Try it: an assert catching a logic bug alongside proper runtime handling
The assert flags the zero-count case as a logic bug that "should never happen" by design, while the separate if-check still protects the division at runtime regardless of whether asserts are compiled in.
Check yourself
1. What is the key difference between what assert() is for, versus what runtime error-code handling is for?
assert() is a development-time tool for catching logic bugs that should never occur if the code is correct, while proper error handling must cover conditions that can genuinely happen even in correct code, like bad external input.