C++ Academy · Lesson

constexpr Functions and if constexpr

Evaluate code at compile time with constexpr and branch with if constexpr.

Lesson 4 of 414 steps

constexpr Functions and if constexpr is a free C++ Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, and your progress syncs across the web and the CoddyKit app. The C++ Academy course includes 4 lessons in total.

Compile-Time Evaluation

The constexpr keyword tells the compiler "evaluate this at compile time when possible." Compile-time computation has zero runtime cost.

constexpr Variables

A constexpr variable must be initialized with a constant expression. The result is fixed at compile time.

constexpr int BUFFER_SIZE = 1024;
constexpr double PI = 3.14159265358979;

constexpr Functions

Mark functions as constexpr to allow them to run at compile time when called with constant arguments.

constexpr int factorial(int n) {
    return (n <= 1) ? 1 : n * factorial(n - 1);
}

constexpr int five_fact = factorial(5);  // computed at compile time

Runtime Fallback

A constexpr function can also be called with runtime values — it runs at runtime in that case.

int n = read_input();
int result = factorial(n);   // runtime call

Restrictions on constexpr Functions

Before C++14:

  • Only one return statement
  • No loops
  • No mutating local state

C++14 relaxed these; C++17 and C++20 added more (try-catch, dynamic alloc, virtuals).

consteval (C++20)

Force compile-time evaluation with consteval. Calling a consteval function with non-constant arguments is an error.

consteval int square(int x) { return x * x; }

constexpr int c = square(5);    // OK
int x = 5;
// int r = square(x);            // ERROR

constinit (C++20)

constinit guarantees the variable is initialized at compile time but allows runtime mutation.

if constexpr (C++17)

if constexpr is a compile-time branch. The non-taken branch is not even compiled — useful for templates.

template <typename T>
void print(const T& value) {
    if constexpr (std::is_pointer_v<T>) {
        std::cout << "pointer: " << *value;
    } else {
        std::cout << value;
    }
}

Eliminating SFINAE

if constexpr replaces complex SFINAE patterns with clear conditional logic. Combined with type traits, it makes generic code far easier to read.

Compile-Time Algorithms

Modern C++ lets you write surprisingly complex algorithms that run entirely at compile time — string hashing, table generation, mini parsers.

constexpr auto fnv1a(std::string_view s) {
    uint32_t h = 2166136261u;
    for (char c : s) {
        h = (h ^ static_cast<uint8_t>(c)) * 16777619u;
    }
    return h;
}

constexpr auto x = fnv1a("hello");

Templates Plus constexpr

Generic constexpr functions are a powerful combination — write generic, type-flexible code that evaluates at compile time.

Diagnostics

Compile-time errors in constexpr code are reported with detailed locations. Modern compilers are quite good at pinpointing the offending step.

Quick Check

What does if constexpr do that a regular if does not?

Recap

constexpr enables compile-time evaluation; consteval enforces it; constinit guarantees compile-time init. if constexpr branches at compile time — the not-taken branch is never instantiated, replacing SFINAE in many cases.

Free to start

Learn C++ with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “constexpr Functions and if constexpr” lesson free?

Yes — any 3 lessons of the C++ Academy learning path, including “constexpr Functions and if constexpr”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The C++ Academy course includes 4 lessons in total.

What will I learn in “constexpr Functions and if constexpr”?

Evaluate code at compile time with constexpr and branch with if constexpr. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

How long does the “constexpr Functions and if constexpr” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Function and Class Templates Revisited
  2. Template Specialization Partial and Full
  3. Variadic Templates and Parameter Packs
  4. constexpr Functions and if constexpr
← Back to C++ Academy