CodeBlanks Logo Icon CodeBlanks

Summary - constexpr

Combine constexpr, consteval and constinit to write a lookup table.

Summary - constexpr

In this group you saw the compile-time tools: constexpr variable, constexpr function, if constexpr, consteval and constinit. All produce values at compile time; the difference is flexibility versus strictness.

Now you will combine them into a constexpr factorial. This function delivers the recursive template's behavior with a constexpr function; constexpr int factorial(int n) is usable at both compile time and run time.

constexpr factorial

Inside a constexpr function you write the base case if (n <= 1) return 1; and the recursive step return n * factorial(n - 1);. When called with a constant argument, the compiler unfolds the chain at compile time.

Example: constexpr int f = factorial(4); produces the constant f = 24. This is the same as the recursive template but without template syntax; the code is readable and can also be called at run time.

Practice Write the constexpr factorial

Write constexpr int factorial(int n). Body: if (n <= 1) return 1; return n * factorial(n - 1);. In main define constexpr int f = factorial(4); and write std::cout << f;.

Starter code

main.cpp
#include <iostream>

// Define the constexpr factorial function here

int main() {
    // Define f and print it
    return 0;
}

Sample solution

main.cpp
#include <iostream>

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

int main() {
    constexpr int f = factorial(4);
    std::cout << f;
    return 0;
}

Expected output

24

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which keyword makes a function run only at compile time?

main.cpp
constexpr int a(int);
consteval int b(int);
constinit int c = 0;
  • consteval Correct answer
  • constinit
  • constexpr
  • const

Explanation: consteval (immediate function) runs only at compile time.

2 Complete the recursive step

Question
constexpr int factorial(int n) { return n * factorial(n - ____); }
Answer
constexpr int factorial(int n) { return n * factorial(n - 1); }

Explanation: n * factorial(n-1) is the recursive step.

3 Match each tool to its trait

Term Meaning
constexpr Flexible compile/run
consteval Compile-time only
constinit Static initialization
if constexpr Compile-time branch

All lessons in Expert