`consteval` — C++ Keyword

`consteval` — C++ Keyword

The consteval keyword in C++20: declares an immediate function that must be evaluated at compile time.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

consteval

Declares an immediate function: every call to it must produce a compile-time constant. If the call cannot be evaluated at compile time, the program is ill-formed (unlike constexpr, which also allows runtime evaluation). Introduced in C++20.

Syntax

consteval return-type func(params) { body }

Example

#include <print>

// Must be evaluated at compile time
consteval int square(int n) {
    return n * n;
}

constexpr int maybe_ct(int n) {
    return n * n;  // can be runtime or compile-time
}

int main() {
    constexpr int a = square(7);   // OK: compile-time
    std::println("{}", a);         // 49

    // int x = 7;
    // int b = square(x);          // error: x is not a constant expression

    int x = 7;
    int b = maybe_ct(x);           // OK: constexpr allows runtime
    std::println("{}", b);         // 49
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}