Modern C++ • C++20 baseline
constexpr, consteval, and Compile-Time Programming
Use compile-time evaluation when it improves validation or removes runtime work.
constexpr permits constant evaluation when the call arguments and operations allow it. consteval requires an immediate compile-time invocation. Both features have restrictions, and compile-time complexity can increase build times. Use static_assert to turn assumptions into compile-time checks.
Key points
- constexpr does not mean every invocation is evaluated at compile time.
- consteval is a stronger requirement and belongs on APIs that must reject runtime inputs.
Example
constexpr unsigned factorial(unsigned value) {
return value < 2 ? 1 : value * factorial(value - 1);
}
static_assert(factorial(5) == 120);
What to expect
The compiler verifies that factorial(5) is 120 during compilation.
Practice exercise
Add a guard for inputs that would overflow unsigned and decide whether the function should be constexpr or consteval.
Key idea: Compile-time code is still code: define its valid inputs and test edge conditions.