# Constant Expressions: constexpr, consteval & constinit

> Distinguish core constant expressions from constant-evaluated contexts, choose cleanly between constexpr, consteval, and constinit, and branch safely with if consteval.

- **Source:** C++ Atlas (https://cppatlas.com/topics/constant-expressions)
- **Track:** Expressions and functions
- **Estimated reading time:** 8 minutes
- **ISO C++ clauses:** [expr.const] (https://eel.is/c++draft/expr.const), [dcl.constexpr] (https://eel.is/c++draft/dcl.constexpr), [dcl.consteval] (https://eel.is/c++draft/dcl.consteval), [dcl.constinit] (https://eel.is/c++draft/dcl.constinit), [stmt.if] (https://eel.is/c++draft/stmt.if), [meta.const.eval] (https://eel.is/c++draft/meta.const.eval)
- **cppreference links:** [Constant expressions](https://en.cppreference.com/w/cpp/language/constant_expression), [constexpr specifier](https://en.cppreference.com/w/cpp/language/constexpr), [consteval specifier](https://en.cppreference.com/w/cpp/language/consteval), [constinit specifier](https://en.cppreference.com/w/cpp/language/constinit), [if statement](https://en.cppreference.com/w/cpp/language/if)
- **Prerequisites:** evaluation-order, initialization-forms

When developers hear "compile-time evaluation," they often picture an aggressive optimizer folding arithmetic constants at `-O2`. In C++, **constant expressions** are something far stronger: a formal part of the language rules defined in `[expr.const]` that governs what the compiler *must* evaluate during translation—even at `-O0`—and when an evaluation error becomes a hard diagnostic.

> **Mental model.** `constexpr` on a function means "permitted in constant evaluation," not "forced at compile time." On a variable, `constexpr` means both "compile-time initialized" and `const`. When you want compile-time initialization *without* `const`, reach for `constinit`; when you want compile-time execution *mandatorily*, reach for `consteval`.

## What makes an expression constant

The standard splits the idea into two layers. First, an expression is a **core constant expression** unless evaluating it runs into a forbidden runtime operation under `[expr.const]/5`. Disqualified operations include calling a non-`constexpr` function, reading an uninitialized scalar or `volatile` glvalue, performing `reinterpret_cast`, throwing an uncaught exception, or triggering **any undefined behavior**.

Second, to serve as a full **constant expression** (for instance, to initialize a `constexpr` variable or size a `std::array`), the result cannot dangle: it cannot point or refer to an automatic local variable or to heap memory that has not been freed before evaluation ends.

Just as important is *when* the compiler is required to evaluate one. The standard calls those places **manifestly constant-evaluated contexts**:

- `static_assert` conditions and `if constexpr (...)` predicates
- Non-type template arguments and array bounds
- Initializers of `constexpr` and `constinit` variables
- Invocations of `consteval` functions
- `const` integral or enumeration variables whose initializers happen to be constant expressions

Outside those contexts, calling a `constexpr` function with literal arguments might evaluate at compile time as an optimization—or might run at runtime under `-O0`.

## constexpr vs. consteval vs. constinit

Mixing up these three specifiers is easy because they share a prefix, yet each solves a distinct problem.

| Specifier | Applies to | Evaluation timing | Resulting object mutable? | Usable with runtime inputs? |
| --- | --- | --- | --- | --- |
| `constexpr` (variable) | Variables (and static data members) | Must be constant-initialized | No (implicitly `const`) | N/A |
| `constexpr` (function) | Functions and constructors | Compile-time *or* runtime | N/A | Yes |
| `consteval` | Functions and constructors | **Always** compile-time | N/A | No (compile error) |
| `constinit` | Static or `thread_local` variables | Must be constant-initialized | **Yes** (unless also `const`) | N/A |

Notice two details in that comparison that routinely trip people up. First, `constexpr` on a function signature never makes the return type `const` (unlike `constexpr` on a variable, where `constexpr int* p` means `int* const p`—top-level `const`!). Second, `constinit` solves the **static initialization order fiasco** for mutable globals and `thread_local` caches: if the initializer is not a valid constant expression, compilation fails immediately instead of silently falling back to dynamic initialization before `main`.

```cpp
consteval int square_now(int n) {
    return n * n;
}

constexpr int square_anytime(int n) {
    return n * n;
}

// Guaranteed static initialization, yet still mutable at runtime.
constinit int global_hits = square_now(4);

// Compile-time constant and implicitly const.
constexpr int table_size = square_anytime(8);
static_assert(table_size == 64);

int runtime_demo(int user_input) {
    global_hits += 1;                        // Legal: constinit is not const
    // int bad = square_now(user_input);     // Error: user_input is not constant
    return square_anytime(user_input);       // Legal: runs at runtime
}
```

## Transient allocation and C++20/23 expansions

Since C++20, constant evaluation supports `new` and `delete`, which enables `constexpr` `std::vector` and `std::string`. There is one strict boundary rule: **transient allocation**. Any dynamic memory allocated during a constant evaluation must be deallocated before that constant evaluation returns its final value (`[expr.const]/5`).

You can build and sort a `std::vector<int>` inside a `constexpr` or `consteval` helper, extract a scalar summary, a fixed `std::array`, or a count, and let the vector's destructor free its buffer before leaving the compile-time evaluator. What you *cannot* do is declare `constexpr std::vector<int> v{1, 2, 3};` at namespace scope, because its heap buffer would attempt to survive past the end of constant evaluation.

```cpp
#include <array>
#include <cstddef>
#include <vector>

consteval int triangular_sum(int n) {
    std::vector<int> scratch;
    for (int i = 1; i <= n; ++i) {
        scratch.push_back(i);
    }
    int sum = 0;
    for (int x : scratch) {
        sum += x;
    }
    return sum; // scratch is destroyed and freed here: valid transient allocation
}

static_assert(triangular_sum(6) == 21);

// To persist compile-time data into the binary, copy into std::array:
consteval std::array<int, 4> make_squares() {
    std::vector<int> tmp{1, 2, 3, 4};
    std::array<int, 4> out{};
    for (std::size_t i = 0; i < out.size(); ++i) {
        out[i] = tmp[i] * tmp[i];
    }
    return out;
}

constexpr auto squares = make_squares();
static_assert(squares[3] == 16);
```

C++23 further widened what can sit inside a `constexpr` function: `static constexpr` variables are now permitted locally, `goto` restrictions eased, and a `constexpr` function no longer causes an error just because *no* valid constant-expression instantiation exists yet (P2448R2).

## Dual-path code with if consteval (C++23)

Sometimes a function needs two implementations: a portable pure-C++ algorithm for compile-time evaluation and a SIMD intrinsic or assembly path at runtime. C++20 introduced `std::is_constant_evaluated()` in `<type_traits>` for that split, and C++23 added a dedicated statement syntax: `if consteval { ... } else { ... }` (notice: **no parentheses** around a condition).

> **Pitfall.** Never write `if constexpr (std::is_constant_evaluated())`. Because the predicate of `if constexpr` is itself a manifestly constant-evaluated context, `std::is_constant_evaluated()` unconditionally evaluates to `true` there—silently discarding your runtime branch even when the outer function is called at runtime.

C++23 `if consteval` eliminates that mistake by syntax alone and adds one capability `if (std::is_constant_evaluated())` lacks: inside the `if consteval` branch, the compiler puts you inside an immediate-function context, allowing direct calls to `consteval` functions using the enclosing function's parameters.

```cpp
#include <type_traits>

consteval int compile_time_hash(int x) { return x * 2654435761u; }
int runtime_crc(int x) { return x ^ 0x5555; }

constexpr int compute_tag(int x) {
    if consteval {
        // Immediate context: calling a consteval function with 'x' is legal here!
        return compile_time_hash(x);
    } else {
        return runtime_crc(x);
    }
}

constexpr int c_tag = compute_tag(7); // Takes the `if consteval` branch

int runtime_tag(int dynamic_x) {
    return compute_tag(dynamic_x);    // Takes the `else` branch
}
```

## Undefined behavior is forbidden at compile time

One underappreciated gift of `constexpr` and `consteval` is that the constant evaluator acts as a built-in undefined-behavior detector. Outside constant evaluation, signed integer overflow, shifting by a negative count, dereferencing a null pointer, reading past the end of an array, or reading an inactive union member can slip silently into compiled machine code. Inside constant evaluation, `[expr.const]/5` rejects *every* core-language undefined behavior with a compile-time diagnostic explaining which rule failed.

> **Standardese.** "An expression `E` is a core constant expression unless the evaluation of `E`, following the rules of the abstract machine, would evaluate one of the following: ... an operation that would have undefined behavior as specified in [intro] through [cpp]." — `[expr.const]`

## What to remember

- **Core constant expressions reject UB.** Any undefined behavior during evaluation turns a constant expression into a guaranteed compile error.
- **Keep the three keywords distinct.** `constexpr` allows compile-time evaluation (and adds `const` to variables), `consteval` requires compile-time evaluation, and `constinit` enforces static initialization on mutable static/thread-local objects.
- **Dynamic memory works if it stays local.** Compile-time `std::vector` and `std::string` allocations are legal as long as they are freed before evaluation returns.
- **Prefer `if consteval` in C++23.** It avoids the `if constexpr (std::is_constant_evaluated())` bug and unlocks calling `consteval` helpers directly.
- **Function `constexpr` is not return `const`.** Always read `constexpr` on a function as an evaluation capability, not a qualifier on its return type.

## Concept Map Outline

- **Constant Expressions:** Compile-time evaluation obeys strict abstract-machine rules governed by constexpr, consteval, and constinit.
  - **Core Constant Rules:** Core constant expressions disallow runtime-only operations, dangling outputs, and all undefined behavior.
    - **No undefined behavior:** Signed overflow, out-of-bounds reads, and inactive union access fail to compile.
    - **No dangling results:** Final constant values cannot point to local stack slots or unfreed heap storage.
    - **Manifestly constant contexts:** static_assert, template arguments, constexpr vars, and consteval calls force compile-time evaluation.
  - **Three Specifiers:** Each keyword controls timing and mutability differently across variables and functions.
    - **constexpr allows compile time:** constexpr functions run at compile time or runtime; constexpr variables are implicitly const.
    - **consteval forces compile time:** Immediate functions execute solely during translation and reject runtime arguments.
    - **constinit enforces static init:** constinit prevents dynamic initialization order bugs while keeping static or thread-local variables mutable.
  - **Transient Allocation:** C++20 allows dynamic allocations inside constant evaluation provided they are freed before returning.
    - **Compile-time new and delete:** Dynamic allocations and deallocations succeed inside constexpr evaluation contexts.
    - **Allocations cannot escape:** Heap pointers from constant evaluation cannot persist into runtime global objects.
    - **Copy to std::array:** Extract results from temporary std::vector buffers into fixed arrays to persist data.
  - **Dual-Path Branching:** Select portable compile-time logic or optimized runtime code within one constexpr function.
    - **std::is_constant_evaluated:** Returns true inside a plain if statement only during constant evaluation.
    - **if constexpr trap:** Wrapping std::is_constant_evaluated inside if constexpr always evaluates to true.
    - **C++23 if consteval:** Enters an immediate context that avoids the trap and permits calling consteval helpers.
  - **Subtle Boundaries:** Specifier placement and function pointers follow rules distinct from ordinary runtime code.
    - **Pointer top-level const:** constexpr on a pointer variable makes the pointer itself const rather than the pointee.
    - **Immediate function pointers:** Taking the runtime address of a consteval function is ill-formed outside constant evaluation.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.constexpr], [dcl.consteval])

Given `constexpr int a(int x) { return x + 1; }` and `consteval int b(int x) { return x + 1; }`, what happens when `main` calls both with a non-constant local `int n = 5;`?

```cpp
constexpr int a(int x) { return x + 1; }
consteval int b(int x) { return x + 1; }

int main() {
    int n = 5;
    int r1 = a(n);
    int r2 = b(n);
    return r1 + r2;
}
```

A. Both `a(n)` and `b(n)` compile and run at runtime.
B. `a(n)` compiles and runs at runtime, while `b(n)` is a compile error.
C. `a(n)` is a compile error because `n` is not constant, while `b(n)` compiles.
D. Both `a(n)` and `b(n)` fail to compile because `n` is not `constexpr`.

**Answer (B):** `a(n)` compiles and runs at runtime, while `b(n)` is a compile error.

**Why:** A `constexpr` function may execute either at compile time or at runtime depending on the call context, so `a(n)` runs cleanly at runtime. A `consteval` function is an immediate function (`[dcl.consteval]`) whose every evaluation must be a compile-time constant expression, so `b(n)` is ill-formed.

### Question 2 [warmup] ([dcl.constinit], [dcl.constexpr])

When should you declare a namespace-scope variable `constinit` instead of `constexpr`?

A. When the variable is a local automatic variable inside a function.
B. When the initializer depends on runtime user input.
C. When you want the variable to have internal linkage automatically.
D. When you want guaranteed static initialization to avoid initialization-order bugs while still mutating the variable at runtime.

**Answer (D):** When you want guaranteed static initialization to avoid initialization-order bugs while still mutating the variable at runtime.

**Why:** `constinit` (`[dcl.constinit]`) requires constant initialization for a variable with static or thread storage duration—preventing dynamic initialization order bugs—without making the variable `const`. `constexpr` makes the variable implicitly `const`.

### Question 3 [tricky] ([stmt.if], [meta.const.eval])

What is the bug in `compute(int x)` below when invoked with a runtime integer `n`?

```cpp
constexpr int compute(int x) {
    if constexpr (std::is_constant_evaluated()) {
        return x * 2;
    } else {
        return x + 1;
    }
}
```

A. `std::is_constant_evaluated()` cannot be called in an `if constexpr` condition.
B. It returns `x + 1` at runtime and `x * 2` at compile time.
C. The `if constexpr` condition is manifestly constant-evaluated, so `std::is_constant_evaluated()` is always `true` and the `else` branch is discarded.
D. The code fails to compile because `x` is not a template parameter.

**Answer (C):** The `if constexpr` condition is manifestly constant-evaluated, so `std::is_constant_evaluated()` is always `true` and the `else` branch is discarded.

**Why:** The condition of `if constexpr` is always evaluated as a constant expression (`[stmt.if]`), so `std::is_constant_evaluated()` unconditionally returns `true` there. Even when `compute(n)` is called at runtime, it executes `x * 2`. Use plain `if (std::is_constant_evaluated())` in C++20 or `if consteval` in C++23.

### Question 4 [tricky] ([expr.const])

Which declaration using `std::vector` compiles cleanly in C++23?

```cpp
consteval std::size_t vec_len() {
    std::vector<int> v{1, 2, 3};
    return v.size();
}
consteval std::vector<int> make_vec() {
    return std::vector<int>{1, 2, 3};
}
```

A. `constexpr std::size_t n = vec_len();` compiles, while `constexpr auto v = make_vec();` fails.
B. Both `constexpr std::size_t n = vec_len();` and `constexpr auto v = make_vec();` compile.
C. Neither compiles because `std::vector` allocates dynamic heap memory.
D. `constexpr auto v = make_vec();` compiles only if `v` is declared `constinit`.

**Answer (A):** `constexpr std::size_t n = vec_len();` compiles, while `constexpr auto v = make_vec();` fails.

**Why:** C++20/23 supports transient allocation (`[expr.const]/5`): compile-time `new` and `delete` are permitted inside `vec_len()` because `v` is destroyed and freed before evaluation completes. Returning `std::vector` into a `constexpr` variable attempts to retain unfreed allocation past constant evaluation, which is ill-formed.

### Question 5 [standardese] ([stmt.if], [expr.const])

Why does calling a `consteval` helper `ce(x)` compile inside `if consteval` in C++23 when it fails inside `if (std::is_constant_evaluated())`?

```cpp
consteval int ce(int v) { return v * 3; }

constexpr int f(int x) {
    if consteval {
        return ce(x);
    }
    return x;
}
```

A. `if consteval` converts the parameter `x` into a template parameter automatically.
B. The compound statement of `if consteval` is an immediate-function context, whereas an ordinary `if` block is not.
C. `std::is_constant_evaluated()` is deprecated in C++23 and forbidden with `consteval`.
D. Inside `if consteval`, `ce(x)` is silently rewritten into a runtime call.

**Answer (B):** The compound statement of `if consteval` is an immediate-function context, whereas an ordinary `if` block is not.

**Why:** Under `[stmt.if]` and `[expr.const]`, the true branch of `if consteval` places expressions in an immediate-function context, allowing calls to `consteval` functions using non-constant parameters of the enclosing `constexpr` function. A plain `if (std::is_constant_evaluated())` does not create an immediate context.

### Question 6 [standardese] ([expr.const], [dcl.constexpr])

What does the C++ standard require when evaluating a `constexpr` variable initializer triggers signed integer overflow (`INT_MAX + 1`)?

```cpp
#include <limits>
constexpr int overflow = std::numeric_limits<int>::max() + 1;
```

A. It wraps around cleanly using two's complement arithmetic.
B. It compiles with a warning and stores an unspecified value.
C. It only fails if `-Werror` or `-fsanitize=undefined` is enabled.
D. The program is ill-formed because any undefined behavior disqualifies a core constant expression.

**Answer (D):** The program is ill-formed because any undefined behavior disqualifies a core constant expression.

**Why:** `[expr.const]/5` explicitly disqualifies any evaluation that triggers undefined behavior in the abstract machine from being a core constant expression. Since `constexpr` requires a constant expression initializer, the compiler must emit a diagnostic.
