Does a C++ constexpr function always run at compile time, and which contexts force a call to be constant-evaluated?
answer
- may, not must
- the context decides
- contexts that require a constant
- same function at run time
- is_constant_evaluated and if consteval
basics
~20 sNo. A constexpr function may be evaluated at compile time, and must be only where the context requires a constant: a constexpr variable's initializer, a template argument, an array bound, static_assert. Called with run-time arguments, the same function runs at run time.
solid answer
~40 s`constexpr` on a function means it *can* be used in constant expressions, not that it always is. A call is constant-evaluated when its context requires a constant: initializing a `constexpr` variable, a template argument, an array bound, a `case` label, `static_assert`, an `if constexpr` condition, or the initializer of a static variable that gets constant initialization. In any other context, such as `crc32(argv[1])`, it is an ordinary function call; the optimizer may still fold it, but nothing guarantees that. If a required evaluation hits something not allowed at compile time, such as a non-constexpr call or undefined behaviour, the program fails to compile. To branch on which evaluation you are in, C++20 has `std::is_constant_evaluated()` and C++23 has `if consteval`; `if constexpr (std::is_constant_evaluated())` is a known bug, because there the call is always `true`.
code
cpp · 30 lines#include <array>
#include <cstdint>
#include <cstdio>
#include <string_view>
constexpr std::array<std::uint32_t, 256> make_crc_table() {
std::array<std::uint32_t, 256> table{};
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;
table[i] = c;
}
return table;
}
constexpr auto kCrcTable = make_crc_table(); // computed by the compiler
constexpr std::uint32_t crc32(std::string_view data) {
std::uint32_t c = 0xFFFFFFFFu;
for (unsigned char b : data) c = kCrcTable[(c ^ b) & 0xFFu] ^ (c >> 8);
return c ^ 0xFFFFFFFFu;
}
static_assert(crc32("123456789") == 0xCBF43926u); // the standard check value
int main(int argc, char** argv) {
std::string_view arg = argc > 1 ? argv[1] : "123456789";
std::printf("%08X\n", crc32(arg)); // same function, run at run time
}go deeper
Recall that constexpr functions may run at compile time and that the same function is callable at run time with ordinary arguments.
List the contexts that force constant evaluation and explain that a failed forced evaluation, including undefined behaviour, is a compile error.
Use is_constant_evaluated or if consteval to swap in run-time-only code, and spot the if constexpr misuse in review.
Decide which tables and validations move to compile time: smaller startup cost and earlier errors against longer builds and constant-evaluation limits.
## constexpr on a function is permission, not a command A `constexpr` function is one the compiler is **allowed** to evaluate during compilation. Whether it actually is depends on the **call site**, not on the declaration. The C++ standard calls an evaluation that must happen during compilation **manifestly constant-evaluated**, and a call is that only in a context that needs a constant: - the initializer of a `constexpr` variable; - a template argument, an array bound, an enumerator value, a `case` label, `alignas`; - the condition of `static_assert` and of `if constexpr`; - a call to a `consteval` function (an immediate invocation); - the initializer of a variable with static or thread storage duration that is **constant-initialized**, which includes a non-`const` global whose initializer happens to be a constant expression. Everywhere else the call is an ordinary run-time call. The optimizer is free to compute it while compiling under the as-if rule, and often does, but that is an optimization, not a guarantee: at `-O0` it typically will not. ## One function, two evaluations A network stack needs CRC-32 both for a lookup table and for checksumming packets: 1. `constexpr auto kCrcTable = make_crc_table();` forces `make_crc_table()` to be evaluated while compiling. The 256-entry table ends up as data in the binary, and no table-building code runs at startup. 2. `static_assert(crc32("123456789") == 0xCBF43926u);` checks the implementation against the standard CRC-32 check value, also while compiling. 3. `crc32(packet_bytes)` in the receive path is the same function, called at run time with run-time data. Nothing had to be written twice. That is the main reason to make a function `constexpr`: one implementation, usable in both worlds. ## What happens when a forced evaluation fails If a manifestly constant-evaluated call reaches something not allowed at compile time, the result is a **compile error** at the context that required the constant, with notes tracing the call chain. Examples: calling a non-`constexpr` function, reading a variable whose value is not known, or an operation with undefined behaviour such as signed overflow. Apple clang 21 rejects `constexpr int big = add(2147483647, 1);` with `value 2147483648 is outside the range of representable values of type 'int'`. Compile-time evaluation diagnoses undefined behaviour in the core language that a run-time call would silently have. ## Knowing which evaluation you are in Sometimes a function wants a different implementation at run time, for example to call a SIMD intrinsic or a hardware CRC instruction that cannot run during compilation. | Tool | Standard | Use | |---|---|---| | `std::is_constant_evaluated()` | C++20, in `<type_traits>` | returns `true` during constant evaluation | | `if consteval { ... } else { ... }` | C++23 | same test, and its first branch may call `consteval` functions | The classic mistake is `if constexpr (std::is_constant_evaluated())`. The condition of `if constexpr` is itself manifestly constant-evaluated, so the call always returns `true` and the run-time branch is discarded. Apple clang 21 warns: `'std::is_constant_evaluated' will always evaluate to 'true' in a manifestly constant-evaluated expression`. Use a plain `if`, or `if consteval`. ## What moving work to compile time buys, and costs - **No startup work.** A table computed during compilation is stored as initialized data in the binary; nothing builds it when the process starts. - **Earlier errors.** A `static_assert` against a known test vector fails the build rather than a test run. - **Diagnosed undefined behaviour.** Core-language undefined behaviour reached during constant evaluation is a compile error. - **Build time.** Every translation unit that evaluates the call pays for it; a large table belongs in one `.cpp` file. - **Evaluation limits.** Compilers cap the work of one evaluation: Clang has `-fconstexpr-steps` and `-fconstexpr-depth`, GCC has `-fconstexpr-ops-limit`, `-fconstexpr-loop-limit` and `-fconstexpr-depth`. Hitting one is usually a sign that the work belongs at run time. - **Debugging.** There is no debugger inside the compiler; the usual technique is to call the same function at run time in a test. ## Interview summary - `constexpr` functions *can* run at compile time; the context decides whether they *must*. - A forced evaluation that cannot complete is a compile error, including core-language undefined behaviour. - The same function is reused at run time with no extra code. - To detect the mode, use `std::is_constant_evaluated()` in a plain `if`, or C++23's `if consteval`.
- Is int x = crc32("abc"); inside a function body evaluated at compile time?Not by the language's rules. A local, non-constexpr variable's initializer is not a context that requires a constant, so it is an ordinary call. The optimizer will probably fold it at `-O2`, but that is not guaranteed. Write `constexpr auto x = crc32("abc");` when you need the guarantee, or `constinit` for a static variable that must stay mutable.
- Why is if constexpr (std::is_constant_evaluated()) a bug?The condition of `if constexpr` is manifestly constant-evaluated, so `std::is_constant_evaluated()` is always `true` there and the else branch is discarded at compile time. The run-time path silently disappears. Use a plain `if (std::is_constant_evaluated())`, or `if consteval` in C++23; Clang warns about the mistake with `-Wconstant-evaluated`.
- What happens if a constexpr function overflows a signed int during constant evaluation?The evaluation is not a constant expression, because an operation with undefined behaviour disqualifies it. If the context requires a constant, the program fails to compile, with a note giving the out-of-range value. The same overflow at run time would be undefined behaviour with no diagnostic.
- constexpr guarantees the function body never executes at run time.
- A constexpr function cannot be called with run-time arguments.
- Undefined behaviour inside constant evaluation just produces some value.
- if constexpr (std::is_constant_evaluated()) selects the run-time branch at run time.
- Compile-time evaluation depends on the -O level.
Assumes C++23 for if consteval; std::is_constant_evaluated is C++20, and the rest holds for C++17 and later.