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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 42: constexpr and consteval | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

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.

4 points
  • Compile‑time constant (`constexpr`)
  • Immediate functions (`consteval`)
  • Use cases for compile‑time evaluation
  • Limitations and newer relaxations

constexpr and consteval

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 function example

constexpr int factorial(int n) {
    return n <= 1 ? 1 : (n * factorial(n - 1));
}
static_assert(factorial(5) == 120, \"Compile‑time check\");

consteval function example (C++20)

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, consteval functions can have try/catch blocks, 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.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 41: Modern C++ Features (C++11/14/17/20)Continue to lesson 43Lesson 43: Concepts (C++20)Back to C++ Course curriculum