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.

In shortCatching programmer-error conditions during development, and deciding what to do with asserts in production.

What's actually going on

assert() vs runtime error handlingassert()For "should be logicallyimpossible" programmer-errorconditionsOften disabled (NDEBUG) inproduction buildsRuntime error handling(return codes)For legitimately possibleruntime failuresMust always be present,including in production
assert() vs runtime error handling

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

A simplified assert-style check for a programmer-error conditionC: edit and run

This models the logic of assert() in plain C, since the real assert() macro is tied to the standard library's NDEBUG behavior.

Careful:Never use assert() as your ONLY protection against a condition that can legitimately occur in production (like invalid external input or a possible hardware fault) — assert() is commonly disabled entirely in release builds via NDEBUG.

Try it: an assert catching a logic bug alongside proper runtime handling

Using an assert-style check for an internal invariant, separate from input validationC: edit and run

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?