CodeBlanks Logo Icon CodeBlanks

consteval

Learn mandatory compile-time with C++20 consteval.

consteval

consteval (C++20) forces a function to run only at compile time. It behaves like constexpr but a call with a variable argument is a compile error. Example: consteval int cube(int x) { return x * x * x; }.

cube(3) becomes 27 at compile time. But int n; std::cin >> n; cube(n); is a compile error, because n is not a compile-time constant. Use consteval when the computation must absolutely happen at compile time.

consteval vs constexpr

constexpr is flexible: with a constant argument it runs at compile time, with a variable argument at run time. consteval is strict: it runs only at compile time; a variable argument is a compile error. Choose consteval when you want a computation baked as a constant in the executable.

For example, if you prepare a table, consteval generates the values at compile time; at run time the table is ready. This shortens the boot time.

Practice Write the consteval cube

Write consteval int cube(int x) with body return x * x * x;. In main define constexpr int v = cube(3); and write std::cout << v;.

Starter code

main.cpp
#include <iostream>

// Define the consteval cube function here

int main() {
    // define v and print it
    return 0;
}

Sample solution

main.cpp
#include <iostream>

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

int main() {
    constexpr int v = cube(3);
    std::cout << v;
    return 0;
}

Expected output

27

Questions and answers

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

1 Complete the keyword

Question
____ int cube(int x) { return x * x * x; }
Answer
consteval int cube(int x) { return x * x * x; }

Explanation: consteval forces compile-time only.

2 Match each call to its result

Term Meaning
cube(1) returns 1
cube(2) returns 8
cube(3) returns 27
cube(4) returns 64

3 When is consteval cube(int n) a compile error?

main.cpp
int n;
std::cin >> n;
int r = cube(n);
  • Never
  • When n is a variable Correct answer
  • When n is constant
  • Only in debug mode

Explanation: consteval gives a compile error with a variable argument.

All lessons in Expert