Lesson 37 of 45 · C++
Lesson 42: constexpr and consteval
Duration: 11 min
Lesson 37 of 45 · C++
Duration: 11 min
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.\n\n---\n\n## constexpr function example\ncpp\nconstexpr int factorial(int n) {\n return n <= 1 ? 1 : (n * factorial(n - 1));\n}\nstatic_assert(factorial(5) == 120, \"Compile‑time check\");\n\n\n## consteval function example (C++20)\ncpp\nconsteval int compileTimeValue() { return 42; }\nint main() {\n constexpr int v = compileTimeValue(); // okay\n // int runtime = compileTimeValue(); // error: consteval function must be used in a constant expression\n std::cout << \"v = \" << v << '\\n';\n return 0;\n}\n\n\nUse 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).\n\n> Tip: Starting with C++23, consteval functions can have try/catch blocks, enabling graceful compile‑time error handling.\n\n---\n\n<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.