Skip to content
LeetQuant
E12 Advanced C++

E12 · Advanced C++ · Lesson 3 of 5

constexpr in Depth

Exactly when the compiler must evaluate code, what C++20 allows inside constant evaluation, is_constant_evaluated and its pitfalls, consteval validation, constinit, compile-time std::vector, and lookup tables proved correct with static_assert.

18 min

Beyond "constexpr may run at compile time"

The Compile-Time Programming lesson in Modern C++ introduced constexpr, consteval, constinit, if constexpr and a power-of-ten table. This lesson answers the follow-up questions an interviewer asks once you have said "constexpr is permission, not a guarantee":

  • Which contexts force constant evaluation?
  • What can a constexpr function do in C++20, and what stops it?
  • How can one function behave differently at compile time and at run time, and why is that dangerous?
  • How do you use dynamic allocation at compile time, and get the result out?
  • How do you prove a table is right, and that it really lives in read-only memory?

Everything below was compiled with Apple clang 17 (c++ -std=c++20 -O2 -Wall).

Manifestly constant-evaluated contexts

An expression is manifestly constant-evaluated when the language requires its value at compile time. These are the contexts:

  • the initialiser of a constexpr variable;
  • template arguments, array bounds, case labels, enumerator values, bit-field widths, alignas arguments;
  • the condition of static_assert and of if constexpr;
  • an argument to a consteval function (an "immediate invocation");
  • the initialiser of a variable with static or thread storage that is constant-initialised (for example with constinit), and of a const integral or reference variable usable in constant expressions.

Everywhere else the compiler may fold a constexpr call under the as-if rule (it usually does at -O2 when the arguments are known), but it is not required to, and there is no diagnostic if it does not. So "is this computed at compile time?" has two different answers: "is it guaranteed?" (only in the contexts above) and "did the optimiser do it?" (look at the assembly).

What C++20 allows inside constant evaluation

C++20 widened constexpr a lot. This compiles, and the static_assert proves the compiler ran it:

#include <string>

struct Fee { virtual constexpr ~Fee() = default; virtual constexpr int bps() const = 0; };
struct Maker : Fee { constexpr int bps() const override { return -2; } };
struct Taker : Fee { constexpr int bps() const override { return 30; } };

constexpr int total_bps() {
    Fee* fees[2] = {new Maker, new Taker};   // new/delete: allowed if freed before the end
    int s = 0;
    for (Fee* f : fees) { s += f->bps(); delete f; }   // virtual call at compile time
    std::string tag = "fees";                // std::string: allowed, transient
    try { s += int(tag.size()); } catch (...) {}       // try block allowed (throwing is not)
    return s;
}
static_assert(total_bps() == 32);

int main() {}

Virtual calls, new/delete, std::string and try blocks are all allowed (−2+30+4=32-2 + 30 + 4 = 32). What is still forbidden is anything whose result the compiler cannot model exactly:

#include <cstdint>
constexpr std::uint32_t bits(float f) { return *reinterpret_cast<std::uint32_t*>(&f); }
constexpr int counter() { static int n = 0; return ++n; }
constexpr int first(const int* p) { return p[3]; }
constexpr int arr[3] = {1, 2, 3};
constexpr auto a = bits(1.0f);
constexpr auto b = counter();
constexpr auto c = first(arr);
int main() {}
notallowed.cpp:2:49: note: reinterpret_cast is not allowed in a constant expression
notallowed.cpp:3:38: note: control flows through the definition of a static variable
notallowed.cpp:4:44: note: read of dereferenced one-past-the-end pointer is not allowed in a constant expression

(Abridged: Clang also reports "constexpr function never produces a constant expression" for the first two functions, and an error at each variable.) The rest of the list: calling a non-constexpr function, actually throwing, goto, reading an inactive union member, reading uninitialised memory, and any undefined behaviour. For type punning use std::bit_cast, which is constexpr; static locals inside constexpr functions arrive only in C++23.

The out-of-bounds read is the useful one. Constant evaluation is a UB detector: run your arithmetic and indexing code through static_assert and the compiler checks every step.

One function, two implementations: std::is_constant_evaluated

std::is_constant_evaluated() (in <type_traits>) returns true when the call is being evaluated in a manifestly constant-evaluated context. The use case is a function with a portable compile-time algorithm and a faster run-time one, such as a library call that is not constexpr (std::sqrt is not constexpr in C++20):

#include <cmath>
#include <cstdio>
#include <type_traits>

// One function, two implementations: a portable loop the compiler can run,
// and the fast library call at run time (std::sqrt is not constexpr in C++20).
constexpr double my_sqrt(double x) {
    if (std::is_constant_evaluated()) {
        double r = x > 1 ? x : 1;
        for (int i = 0; i < 60; ++i) r = 0.5 * (r + x / r);   // Newton's method
        return r;
    }
    return std::sqrt(x);
}

constexpr double kSqrt2 = my_sqrt(2.0);        // constant context: loop branch
static_assert(kSqrt2 > 1.41421356 && kSqrt2 < 1.41421357);

int main(int argc, char**) {
    double rt = my_sqrt(argc + 1.0);           // run time: std::sqrt branch
    std::printf("%.17g\n%.17g\n", kSqrt2, rt);
    const double c = my_sqrt(2.0);             // not required to be constant: which branch?
    std::printf("%.17g\n", c);
}
1.4142135623730949
1.4142135623730951
1.4142135623730951

Two lessons in three lines of output:

  1. The branches disagree. Newton's iteration settles on 1.4142135623730949, while std::sqrt(2.0) returns the correctly rounded 1.4142135623730951. They differ by exactly one unit in the last place (checked in Python with math.ulp). Code that compares a compile-time constant with a run-time result would fail. If you write two branches, they must be bit-identical, or the difference must be harmless and documented.
  2. The third call ran at run time. c is a local const double: it is not a constexpr variable and not a const integral type, so its initialiser is not manifestly constant-evaluated, and is_constant_evaluated() returned false. The optimiser may still have folded std::sqrt(2.0), but it must fold it as the run-time branch.

The classic mistake is if constexpr (std::is_constant_evaluated()): the condition of if constexpr is itself a constant context, so it is always true. Clang warns: "'std::is_constant_evaluated' will always evaluate to 'true' in a manifestly constant-evaluated expression". Use a plain if. (C++23 adds if consteval for this.)

Worked example

a consteval constructor that validates literals

Order-entry code is full of hard-coded tickers like "AAPL". Design a Symbol type, packed into one 64-bit integer, such that a malformed literal (lower case, empty, more than 8 characters) is a compile error, and say what the packed value of "AAPL" is.

Show solution

Make the constructor consteval. Every Symbol s = "..." is then an immediate invocation, evaluated by the compiler even when s is an ordinary variable. To fail, call a function that is not constexpr: that is not allowed in constant evaluation, so it becomes an error that points at the bad literal.

#include <cstdint>
#include <cstdio>

void invalid_symbol();   // never defined; calling it during constant evaluation is an error

// An 8-byte ticker packed into an integer, validated by the compiler.
struct Symbol {
    std::uint64_t code = 0;
    consteval Symbol(const char* s) {
        int n = 0;
        for (; s[n]; ++n) {
            if (n == 8 || s[n] < 'A' || s[n] > 'Z') invalid_symbol();
            code |= std::uint64_t(static_cast<unsigned char>(s[n])) << (8 * n);
        }
        if (n == 0) invalid_symbol();
    }
};

int main() {
    constexpr Symbol aapl = "AAPL";
    Symbol msft = "MSFT";               // still compile time: the constructor is consteval
    std::printf("%016llX %016llX\n", (unsigned long long)aapl.code, (unsigned long long)msft.code);
    // Symbol bad = "aapl";             // compile error, see below
}
000000004C504141 000000005446534D

The packing puts character ii in byte ii, so "AAPL" is 0x41+0x41⋅28+0x50⋅216+0x4C⋅224\texttt{0x41} + \texttt{0x41} \cdot 2^{8} + \texttt{0x50} \cdot 2^{16} + \texttt{0x4C} \cdot 2^{24}, printed most significant byte first as 4C504141 (the same as Python's int.from_bytes(b"AAPL", "little")). Uncommenting the bad line gives:

symbol_bad.cpp:23:18: error: call to consteval function 'Symbol::Symbol' is not a constant expression
symbol_bad.cpp:12:53: note: non-constexpr function 'invalid_symbol' cannot be used in a constant expression

This is the same technique std::format uses to check format strings at compile time. The trade-off: a consteval constructor cannot accept run-time strings at all, so symbols read from a file need a second, run-time-checked factory function.

constinit and the static initialisation order problem

Globals with dynamic initialisers run before main in an order that is unspecified across translation units. If a.cpp's global constructor reads b.cpp's global before it has been initialised, it sees zero or garbage: the "static initialisation order fiasco". Variables that are constant-initialised are immune, because their values are in the binary before any code runs.

constinit asserts constant initialisation and makes it a compile error if it does not hold, without making the variable const:

#include <cstdio>
#include <cstdlib>

constexpr int default_depth() { return 10; }
int env_depth() { const char* s = std::getenv("BOOK_DEPTH"); return s ? std::atoi(s) : 10; }

constinit int g_depth = default_depth();   // OK: constant initialiser, no start-up code, still mutable
// constinit int g_bad = env_depth();      // error: needs a run-time call
thread_local constinit int t_seq = 0;      // thread_local without a guard check on each access

int main() {
    g_depth = 20;                           // constinit is not const
    ++t_seq;
    std::printf("depth %d, seq %d\n", g_depth, t_seq);
}
depth 20, seq 1

Uncommenting g_bad gives "variable does not have a constant initializer ... non-constexpr function 'env_depth' cannot be used in a constant expression". On a thread_local, constinit also lets the compiler skip the per-access "has this thread initialised it yet?" check, which matters for hot per-thread counters.

Compile-time containers: transient allocation

In C++20 std::vector and std::string work during constant evaluation, under one rule: every allocation must be freed before the evaluation ends. A constexpr std::vector<int> v = {1, 2, 3}; at namespace scope is rejected ("pointer to subobject of heap-allocated object is not a constant expression ... heap allocation performed here"), because the memory would have to outlive the compiler.

The standard workaround is two passes: compute with a vector, read its size into a constant, then copy into a std::array of that size, which can persist.

#include <algorithm>
#include <array>
#include <cstdio>
#include <vector>

// C++20: std::vector works inside constant evaluation, as long as every
// allocation is freed before the evaluation ends ("transient" allocation).
constexpr std::vector<int> primes_below(int n) {
    std::vector<bool> composite(n, false);
    std::vector<int> out;
    for (int i = 2; i < n; ++i) {
        if (composite[i]) continue;
        out.push_back(i);
        for (long j = long(i) * i; j < n; j += i) composite[j] = true;
    }
    return out;
}

// Step 1: run the algorithm once just to learn the size.
constexpr std::size_t kCount = primes_below(1000).size();
// Step 2: run it again and copy into a fixed-size array, which may persist.
constexpr auto kPrimes = [] {
    std::array<int, kCount> a{};
    auto v = primes_below(1000);
    std::copy(v.begin(), v.end(), a.begin());
    return a;
}();

static_assert(kCount == 168);
static_assert(kPrimes.front() == 2 && kPrimes.back() == 997);
static_assert(std::ranges::is_sorted(kPrimes));

int main() {
    std::printf("%zu primes below 1000, last %d\n", kPrimes.size(), kPrimes.back());
}
168 primes below 1000, last 997

There are 168 primes below 1000 (the prime-counting function π(1000)=168\pi(1000) = 168), the largest is 997, and std::ranges::is_sorted runs at compile time too. The sieve runs twice during compilation, which is fine at this size; for large tables, watch build time and Clang's -fconstexpr-steps limit.

Worked example

a CRC-32 table built, tested and placed by the compiler

A feed handler checksums packets with CRC-32 (the IEEE polynomial, as used by zlib and Ethernet). Build the 256-entry table at compile time, prove it correct on every build, and show that it costs nothing at start-up.

Show solution

The table entry for byte ii is ii run through 8 rounds of "if the low bit is set, shift right and XOR with the reflected polynomial 0xEDB88320, else just shift". Write that as a constexpr function and test it against the published check value: the CRC-32 of the ASCII string "123456789" is 0xCBF43926.

#include <array>
#include <cstdint>
#include <cstdio>
#include <string_view>

// CRC-32 (IEEE, reflected polynomial 0xEDB88320) with its 256-entry table built by the compiler.
constexpr std::array<std::uint32_t, 256> make_crc_table() {
    std::array<std::uint32_t, 256> t{};
    for (std::uint32_t i = 0; i < 256; ++i) {
        std::uint32_t c = i;
        for (int k = 0; k < 8; ++k) c = (c & 1) ? 0xEDB88320u ^ (c >> 1) : c >> 1;
        t[i] = c;
    }
    return t;
}
constexpr auto kCrcTable = make_crc_table();

constexpr std::uint32_t crc32(std::string_view s) {
    std::uint32_t c = 0xFFFFFFFFu;
    for (unsigned char ch : s) c = kCrcTable[(c ^ ch) & 0xFF] ^ (c >> 8);
    return c ^ 0xFFFFFFFFu;
}

// Tests that run on every build.
static_assert(kCrcTable[1] == 0x77073096u);
static_assert(crc32("123456789") == 0xCBF43926u);   // the published CRC-32 check value
static_assert(crc32("") == 0);

int main(int argc, char** argv) {
    std::string_view msg = argc > 1 ? argv[1] : "8=FIX.4.4";
    std::printf("crc32(\"%.*s\") = 0x%08X\n", int(msg.size()), msg.data(), crc32(msg));  // run time
}
$ ./crc
crc32("8=FIX.4.4") = 0x23FBC7FD
$ ./crc 123456789
crc32("123456789") = 0xCBF43926

Verification on three levels:

  1. Compile time: the three static_asserts run the real code on every build. A typo in the polynomial or the shift breaks the build, not production.
  2. Independent implementation: Python's zlib.crc32(b"8=FIX.4.4") also gives 0x23fbc7fd, so the run-time path agrees with a reference.
  3. Placement: nm -m crc lists (__TEXT,__const) non-external __ZL9kCrcTable, and otool -s __TEXT __const crc shows the section starting 00000000 77073096 ee0e612c 990951ba, the first four table entries. The table is read-only data in the executable: no constructor, no start-up work, no initialisation-order risk.

The function crc32 itself is constexpr but is called with a run-time string in main, so it runs at run time, reading the precomputed table. That is the usual split: compile-time tables, run-time lookups.

Knowledge check

Which of these guarantees that a constexpr function call is evaluated at compile time?

Knowledge check

Why is constexpr std::vector<int> v = {1, 2, 3}; at namespace scope rejected in C++20?

Knowledge check

What does if constexpr (std::is_constant_evaluated()) do inside a constexpr function?

Key takeaways

  • Only manifestly constant-evaluated contexts (constexpr variables, template arguments, array bounds, case labels, static_assert, consteval calls, constant initialisation) guarantee compile-time evaluation; elsewhere it is an optimisation.
  • C++20 constant evaluation allows virtual calls, try, and transient new/delete, std::vector and std::string; it forbids reinterpret_cast, non-constexpr calls and all UB, which makes it a bug detector.
  • std::is_constant_evaluated lets two implementations share a name; make them agree (Newton vs std::sqrt differed by one ulp) and never test it with if constexpr.
  • A consteval constructor turns bad literals into compile errors; constinit removes start-up order bugs and thread-local guard checks.
  • Build tables with constexpr, test them with static_assert against known values, and check with nm/otool that they landed in read-only data.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).