Lesson 42 of 45
C++Lesson 42: constexpr and consteval
11 min
Course progress93%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 42 of 45
C++11 min
Keep these ideas in mind as you work through the lesson.
constexpr marks functions and variables that can be evaluated at compile time if given constant arguments. consteval (C++20) forces a function to be evaluated immediately during compilation.
constexpr int factorial(int n) {
return n <= 1 ? 1 : (n * factorial(n - 1));
}
static_assert(factorial(5) == 120, \"Compile‑time check\");
consteval int compileTimeValue() { return 42; }
int main() {
constexpr int v = compileTimeValue(); // okay
// int runtime = compileTimeValue(); // error: consteval function must be used in a constant expression
std::cout << \"v = \" << v << '\
';
return 0;
}
Use constexpr when you want both compile‑time and run‑time usability. Use consteval when a value must be known at compile time (e.g., for template arguments).
Tip: Starting with C++23,
constevalfunctions can havetry/catchblocks, enabling graceful compile‑time error handling.
<Alert type="warning">Only a limited set of operations are allowed in a constexpr context (no dynamic allocation, no I/O). The rules have been relaxed in recent standards.