Skip to content
Tutorials Center
My learning

Topics

Lesson 91 of 171 ยท Templates and Generic Programming

Compile-Time Programming: constexpr and consteval

Learn C++ compile-time programming - constexpr functions, if constexpr, consteval and if consteval, static_assert, and building lookup tables while your code compiles.

C++ lets you run ordinary-looking code while your program compiles. The result is baked into the executable as a constant, so at run time it costs nothing: no computation, no initialization order problems, and often no memory beyond the final value. A table of precomputed values, a parsed configuration string, or a checksum of a literal can all be produced by the compiler instead of at startup.

You met constexpr variables and got a preview of constexpr functions in Constants: const, constexpr and consteval. This lesson goes deeper: what a constexpr function may contain in modern C++, how to force compile-time evaluation, consteval and if consteval, static_assert for compile-time checks, if constexpr for choosing code paths by type in templates, and building whole lookup tables at compile time.

constexpr functions

A constexpr function can be evaluated at compile time when its arguments are constants and the result is needed in a constant context. It can also be called at run time like a normal function with non-constant arguments. You write one function and get both.

C++ One function, two evaluation times

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

What forces compile-time evaluation is the context, not the function: initializing a constexpr variable, a static_assert, a template argument, an array bound, a case label. A call like factorial(10) in an ordinary expression may be folded by the optimizer, but nothing guarantees it. If you want a guarantee, store the result in a constexpr variable.

What a constexpr function may do

The rules have been relaxed in every standard. In C++23 with GCC 15, a constexpr function can use:

  • local variables, loops, if/switch, recursion and early returns (C++14);
  • std::array, std::string_view, std::optional, std::pair, most of <algorithm> (C++20);
  • std::vector and std::string, as long as the memory is freed before the evaluation ends (C++20 "transient allocation"): you can build a vector inside, but you can't return it into a constexpr variable;
  • virtual function calls, try/catch blocks (but not a throw that is actually reached), and dynamic_cast (C++20);
  • static constexpr local variables, goto and labels, and non-literal variables in branches that aren't evaluated (C++23).

What is never allowed during compile-time evaluation: undefined behavior (the compiler must diagnose it, which makes constexpr a free UB detector), reading a non-constant global, I/O, reinterpret_cast, and calling a non-constexpr function.

C++ The compiler refuses undefined behavior

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Uncomment the first line and the build fails inside std::array::operator[]: GCC's library has a bounds assertion that is skipped at run time in normal builds, but during constant evaluation it shows up as call to non-'constexpr' function 'void std::__glibcxx_assert_fail()'. (With a plain C array the message is about reading outside the array.) The overflow line gives overflow in constant expression. Writing unit tests as static_asserts on constexpr functions catches this whole class of bugs during the build.

static_assert

static_assert(condition, "message") checks a condition at compile time and stops the build with your message if it's false. The message is optional since C++17. Use it to document and enforce assumptions:

C++
static_assert(sizeof(void*) == 8, "this code assumes a 64-bit platform");
static_assert(std::numeric_limits<double>::is_iec559, "IEEE 754 doubles required");
static_assert(sizeof(PacketHeader) == 16);   // a binary file format depends on it

template <typename T>
class RingBuffer {
    static_assert(std::is_nothrow_move_constructible_v<T>,
                  "RingBuffer<T> needs a noexcept move constructor");
};

In C++23 the message must be a string literal; C++26 also allows a computed message (for example a constexpr std::string). Inside templates, a static_assert is checked when the template is instantiated, so it reports errors with the actual type in the message.

consteval and if consteval

Sometimes "may run at compile time" isn't enough: you want a function that must run at compile time, so a mistake becomes a build error rather than a runtime surprise. That's consteval (C++20). Every call to a consteval function (an immediate function) must produce a constant.

C++23 adds if consteval { ... } else { ... }, which lets a constexpr function take a different path depending on whether it's currently being evaluated at compile time. It replaces the older std::is_constant_evaluated().

C++ consteval and if consteval

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A reached throw inside a compile-time evaluation isn't an exception; it just means "this isn't a constant expression", so the build fails with expression '<throw-expression>' is not a constant expression and GCC shows the line with the throw, including its message string. That makes consteval functions ideal for validating literals: format strings (this is exactly how std::format checks "{}" against the argument count at compile time), units, IP addresses, regular-expression patterns.

Which to choose:

Keyword Meaning Use for
constexpr function can run at compile time or at run time most functions that compute values
consteval function must run at compile time validating literals, generating constants
constexpr variable initialized at compile time, and const named constants, tables
constinit variable initialized at compile time, but mutable globals that must avoid the static initialization order problem

if constexpr

if constexpr (condition) evaluates its condition at compile time and discards the branch that isn't taken. Inside a template, a discarded branch isn't instantiated, so it may contain code that wouldn't compile for the current type. That's the difference from a plain if, where both branches must compile.

C++ if constexpr chooses code by type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The static_assert(false, ...) in the final branch fires only if that branch is instantiated. This is allowed since a C++23 change (GCC 13 and later); in older code you'll see workarounds like static_assert(sizeof(T) == 0, ...) to make the condition depend on T.

Outside templates, if constexpr still skips the untaken branch, but that branch must compile anyway, because nothing in it depends on a template parameter. Its power is in templates. Compared with template specialization or overloading, it keeps small type-dependent differences together in one function body; for big differences, separate overloads constrained with concepts read better.

Compile-time lookup tables

A classic use of constexpr is generating a table once, at compile time, and indexing it at run time. A function returning a std::array filled by a loop is all you need. The table lands in the read-only data section of the executable, exactly as if you had typed out every value, but you can't make a typo.

C++ A compile-time CRC-32 table and prime sieve

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The two static_asserts are tests that run during compilation: if someone breaks crc32, the program won't build. The compiler has limits on how much work it does at compile time (by default GCC allows 262,144 iterations per loop and about 33 million operations per evaluation, adjustable with -fconstexpr-loop-limit and -fconstexpr-ops-limit), and heavy compile-time work slows down every build. Precompute tables of thousands of entries, not billions.

Guidelines

  • Mark functions constexpr generously when they're pure computations. It costs nothing at run time and enables compile-time use and static_assert tests.
  • Force evaluation explicitly with a constexpr variable when you need it done at compile time; don't rely on the optimizer.
  • Use consteval when a runtime call would be a bug, typically for validating literals.
  • Use if constexpr inside templates for small type-dependent branches; for large differences, prefer overloads with concepts.
  • Don't confuse constexpr (a promise about when a value can be known) with const (a promise not to modify). A constexpr variable is always const; a const variable may be initialized at run time.
  • C++26 adds constexpr std::sqrt and other math functions, and static reflection, which will make far more compile-time programming possible. Not available yet in GCC 15's C++23 mode.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. constexpr int square(int x) { return x * x; } is called as square(n) where n is read from std::cin. What happens?

    A constexpr function can be called with runtime arguments; it is then evaluated at run time. Only consteval functions require constant arguments.
  2. 2. Which statement guarantees that factorial(10) is evaluated at compile time?

    A constexpr variable must be initialized by a constant expression, so the compiler must evaluate the call. Other forms may be folded by the optimizer but are not guaranteed.
  3. 3. A consteval function reaches a throw expression during a compile-time call. What happens?

    During constant evaluation, reaching a throw makes the expression non-constant. For a consteval call (or a constexpr variable) that is a compile error.
  4. 4. Inside template <typename T> auto get(const T& x), why does if constexpr (std::is_pointer_v<T>) return *x; else return x; compile for T = int, but the same code with a plain if does not?

    With a plain if, both branches are instantiated and *x is invalid for an int. if constexpr discards the branch whose condition is false, so it is not instantiated.
  5. 5. You try to evaluate an out-of-bounds std::array access inside a constexpr variable's initializer. What does GCC do?

    Compilers must diagnose undefined behavior during constant evaluation, which makes constexpr evaluation and static_assert tests a useful bug detector.

Summary

  • A constexpr function can run at compile time when used in a constant context and at run time otherwise; constant contexts include constexpr variables, static_assert, template arguments and array bounds.
  • Modern constexpr functions allow loops, local variables, std::array, most algorithms and even transient std::vector/std::string; undefined behavior is rejected at compile time.
  • consteval functions must run at compile time; if consteval (C++23) lets a constexpr function choose a compile-time or run-time path.
  • static_assert checks conditions during the build; use it for platform assumptions and as compile-time unit tests.
  • if constexpr discards the untaken branch in templates, so each branch only needs to compile for the types that reach it.
  • Generate lookup tables with constexpr functions returning std::array; keep compile-time work modest so builds stay fast.

Next: Type Traits and Metaprogramming, the toolkit for asking questions about types at compile time.