liveBook · Manning

Static_assert

As explained in Modern C, Third Edition

A static assertion is a C compile-time check that requires a constant Boolean condition to be true and otherwise produces a diagnostic.

static_assert checks a Boolean expression during compilation. If the condition is false, compilation produces a diagnostic instead of allowing the program to proceed. section 8.1.5

Checking a platform assumption

static_assert(sizeof(double) == sizeof(long double), "Extra precision needed for convergence."); This assertion records a required size relationship. The condition is evaluated after preprocessing, during a later compilation phase. section 8.1.5

Keep these distinctions in mind:

  • Use a preprocessor conditional for conditions the preprocessor can evaluate; use static_assert for more sophisticated compile-time conditions known only during compilation. section 8.1.5
  • Write _Static_assert before C23; static_assert was provided as a macro by <assert.h> before becoming the keyword spelling in C23. section 8.1.5
  • Do not confuse static_assert with assert: assert checks a Boolean expression while the program runs, whereas static_assert checks during compilation. section 8.8
static_assert(sizeof(double) == sizeof(long double),
  "Extra precision needed for convergence.");

Inspect the compact assertion that checks platform type-size assumptions. section 8.1.5

How Modern C, Third Edition covers it

How deep it goes
Explains compilation timing, spelling history, and runtime contrast, but does not develop broader assertion design.
Examples
Uses a sizeof comparison to require double and long double to have equal sizes for numerical convergence.
What it assumes
Assumes familiarity with preprocessing and compilation phases while distinguishing runtime assertions from zero.
What you can do after
Apply compile-time checks to reject incompatible platform assumptions before runtime.
How it connects
Connects static_assert with preprocessor conditionals, compile-time assertions, runtime assertions, assert, and NDEBUG.

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.