Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

consteval — immediate functions

consteval declares an immediate function: its calls require constant evaluation, with exceptions that let such computations be composed. Unlike constexpr, it does not provide an ordinary runtime execution path for the function. if consteval distinguishes constant-evaluation contexts from runtime evaluation.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

consteval return_type name(parameters) { /* body */ }
if consteval { /* constant evaluation */ } else { /* runtime evaluation */ }

consteval applies to function and function-template declarations, not variables. It declares an immediate function. An ordinary potentially evaluated call outside an immediate function context must be a constant expression; an optimizer merely being able to precompute the result is insufficient. In contrast, constexpr allows the same function to participate in both constant evaluation and runtime execution.

Inside an immediate function, parameters can be passed to other immediate functions: the constant-expression requirement applies to the enclosing immediate invocation. This does not make a parameter a constexpr variable. A consteval result can also initialize an ordinary mutable variable—the restriction concerns the computation, not the result's subsequent mutability.

if consteval selects its first block in a manifestly constant-evaluated context and its else block otherwise. The first block is an immediate function context, so square(x) inside evaluate is permitted. Both branches require braces. This is not if constexpr: it does not discard a branch during template instantiation based on a constant condition.

In the example, evaluate(6) is constant-evaluated, whereas evaluate(x) uses the runtime path. A direct square(x) in main is ill-formed because reading that local variable is not a constant expression. All declarations of the same function must retain the consteval specifier; it cannot be combined with constexpr in one declaration. The source is an evolving working draft, not a frozen C++23 edition; the example targets local verification in C++23 mode, with no production runtime attested.

Examples

#include <iostream>

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

constexpr int evaluate(int x) {
    if consteval {
        return square(x);
    } else {
        return x * x;
    }
}

int main() {
    constexpr int a = evaluate(6);
    static_assert(a == 36);
    int x = 7;
    std::cout << a << ' ' << evaluate(x) << '\n';
    // square(x); // ill-formed
}

Result

36 49

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources