liveBook · Manning

Constexpr

As explained in 100 C++ Mistakes and How to Avoid Them

constexpr is a C++ specifier that permits a variable or function to participate in compile-time constant evaluation when its requirements are satisfied.

constexpr lets a variable or function participate in compile-time constant evaluation when its requirements are satisfied. Unlike a macro, it keeps the compiler involved, enabling type checking and compile-time evaluation. section 5.2

Replacing an untyped constant macro

A macro such as #define PI 3.1415927 hides the value's type from the compiler. Replacing macro-based constants with modern C++ constant expressions makes type assumptions visible and errors diagnosable during compilation. section 5.2

Listing 5.3 Using macros to define, reduce, and add types
#define PI 3.1415927                                         #1
#define SQUARE(n) n * n                                      #2
#define FOR(a, b) for (i = a; i < b; ++i);                   #3
#define FALSE 0                                              #4
#define TRUE !FALSE
 
int main() {
    int n = 3;
    std::cout << SQUARE(n) << '\n';
    std::cout << SQUARE(n + (n - 1)) << '\n';
    std::cout << SQUARE(++n) << '\n';
 
    int i;
    FOR(0, 10)
        std::cout << i << '\n';
 
    int truth = FALSE;    
    ++truth;                                                 #5
    ++truth;
 
    if (truth == FALSE)
        std::cout << "smooth\n";
    else
        std::cout << "dismay\n";
    return 0;
}

Compare the macro-based constant with the surrounding macro examples to see why untyped substitution can obscure correctness. section 5.2

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Defines compile-time evaluation and type guarantees but does not detail constexpr function requirements or implementation internals.
Examples
Uses a PI constant and contrasts macro-based code with C++ constructs that involve compiler checking.
What it assumes
Assumes basic C++ syntax and compiler checking while introducing a safer alternative to macros.
What you can do after
Apply constexpr to express compile-time values while exposing type mismatches to the compiler.
How it connects
Connects constexpr with macros, compile-time evaluation, type checking, templates, and implicit type conversions.

Also explained in

Compare how 3 books explain constexpr →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.