liveBook · Manning

Assertion

As explained in Modern C, Third Edition

assert is a C standard-library assertion macro that evaluates a runtime condition and calls abort when the condition is false.

In C, assert is a runtime assertion macro from <assert.h>. It evaluates a Boolean expression whenever execution reaches it, unless NDEBUG is defined during compilation. If the expression is false, assert prints a diagnostic message and calls abort. section 8.8

Checking a function precondition

A recursive greatest-common-divisor function begins with assert(a <= b). This makes its required argument relationship explicit: an invalid initial call produces an informative failure instead of silently continuing. Recursive calls preserve the condition through the modulus operation. section 7.3

inline size_t gcd2(size_t a, size_t b) [[__unsequenced__]] {  1 
  assert(a <= b);               2  
  if (!a) return b;    3  
  size_t r = b % a;            4  
  return gcd2(r, a);     
}

Inspect the assertion at the start of gcd2, alongside its termination check, remainder calculation, and recursive call. section 7.3

Use assertions according to these rules:

  • Assert properties that are supposed to hold at a particular runtime point, including dynamic conditions and function preconditions. section 8.8
  • Keep assertions active during debugging so false assumptions about variable values lead to diagnostic output and a failure location. section 8.8
  • Define NDEBUG only for a production compilation when assertions should not evaluate expressions or call abort; therefore, do not rely on assert expressions for required program effects. section 8.8
  • Prefer static_assert for compile-time Boolean checks; use assert for conditions that must be tested during execution. section 8.8

How Modern C, Third Edition covers it

How deep it goes
Explains evaluation, diagnostics, abort, and NDEBUG disabling, but stops short of implementation details for the macro itself.
Examples
Uses gcd2 precondition checks and the diagnostic produced when an assertion fails.
What it assumes
Assumes basic C expressions, functions, and compilation, while distinguishing runtime checks from compile-time assertions.
What you can do after
Diagnose debugging-time violations of runtime assumptions and make function preconditions explicit.
How it connects
Connects assertions with preconditions, static_assert, NDEBUG, debugging, and abort.

Also explained in

Compare how 15 books explain assertion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.