Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 37 of 45 · C++

Lesson 42: constexpr and consteval

Duration: 11 min

constexpr and consteval\n\nconstexpr 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.

Previous: Lesson 41: Modern C++ Features (C++11/14/17/20)Next: Lesson 43: Concepts (C++20)