consteval
- C++ course
- Expert
- Lesson 10/47
- 5 min
Learn immediate functions with C++20 consteval.
consteval
consteval (C++20) declares an immediate function. This function must be evaluated at compile time. Example: consteval int square(int x) { return x * x; }.
The call constexpr int s = square(5); produces 25 at compile time. But int n = readInput(); int r = square(n); is a compile error: consteval rejects run-time arguments. Unlike constexpr, consteval is not flexible; it is strict.
consteval versus constexpr
The difference between consteval and constexpr is flexibility. A constexpr function can run at both compile time and run time; consteval runs only at compile time.
If you turn a constexpr function into consteval, old run-time calls become compile errors. Use consteval when you want a compile-time guarantee: encryption tables, constant configuration, format strings. Errors are caught early; run-time cost is zero.
Practice Write the consteval square function
Write consteval int square(int x) with body return x * x;. In main define constexpr int s = square(6); and write std::cout << s;.
Starter code
#include <iostream>
// Define the consteval square function here
int main() {
// Define s and print it
return 0;
}Sample solution
#include <iostream>
consteval int square(int x) {
return x * x;
}
int main() {
constexpr int s = square(6);
std::cout << s;
return 0;
}Expected output
36
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if you call a consteval function with a run-time variable?
consteval int square(int x) { return x * x; }
int n = readInput();
int r = square(n);- It runs at run time
- A warning is issued but it compiles
- It gives a compile error Correct answer
- It becomes constexpr automatically
Explanation: consteval rejects run-time arguments; it gives a compile error.
2 Complete the consteval body
consteval int doubleIt(int x) { return x * ____; }
consteval int doubleIt(int x) { return x * 2; }
Explanation: Write return x * 2;; the multiplier for double is 2.
3 Match each keyword to its trait
| Term | Meaning |
|---|---|
consteval |
Always compile time |
constexpr |
Compile or run time |
constinit |
Static initialization |
if constexpr |
Compile-time branch |