liveBook · Manning

Constexpr

As explained in Modern C, Third Edition

constexpr is a C23 language construct for declaring entities whose values or initialization satisfy compile-time constant-expression requirements.

constexpr is a C23 construct for declarations and compound literals whose values are fixed and known during compilation. Unlike a merely const-qualified object, a constexpr object is guaranteed not to change and supplies a compile-time constant. section 5.6.1 section 5.6.5

A named compile-time constant

constexpr double π = 3.141'592'653'589'793'238'46; declares a read-only double whose value is fixed for the whole compilation. The initializer must fit the declared type exactly: constexpr unsigned πflat = 3.141'592'653'589'793'238'46; is an error because conversion loses significant digits. section 5.6.5

Use constexpr to satisfy compile-time constant requirements:

  • Declare named constants for values that must be known during compilation, including values used in file-scope initializers. section 5.6.1 section 5.6.5
  • Use constexpr objects in integer constant expressions; unlike ordinary const objects, they may participate as evaluated operands. section 5.6.2
  • Apply constexpr to compound literals, including arrays; array elements receive their indicated values and remaining character positions are filled with zeros. section 5.6.5
  • Treat exact type fit as a validity rule: a conversion that changes the initializer's value is rejected at the declaration. section 5.6.5
# define CORVID_NAMES /**/         \
(constexpr char[8][corvid_num]){    \
  [chough] = "chough",             \
  [raven] = "raven",               \
  [magpie] = "magpie",             \
  [jay] = "jay",                   \
}

Inspect a constexpr compound literal representing an array of fixed-size character arrays, with designated entries for corvid names. section 5.6.5

How Modern C, Third Edition covers it

How deep it goes
Explains read-only guarantees, exact type fitting, integer constant-expression use, compound literals, and possible storage optimization.
Examples
Demonstrates π, an invalid unsigned conversion, a corvid-name array compound literal, and constexpr operands in enumeration expressions.
What it assumes
Assumes familiarity with const-qualified objects, literals, arrays, compound literals, macros, and enumeration constants.
What you can do after
Evaluate/understand which C23 objects and expressions qualify as compile-time constants and diagnose value-changing initializations.
How it connects
Connects constexpr with const qualification, constant expressions, integer constant expressions, compound literals, macros, and enumeration constants.

Also explained in

Compare how 3 books explain constexpr →

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.