0Pricing
C++ Academy · Lesson

constexpr Functions and if constexpr

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

constexpr Functions and if constexpr is a free C++ Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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.

Frequently asked questions

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

Yes — the full text of “constexpr Functions and if constexpr” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.

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; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

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