# consteval specifier (since C++20)

From cppreference.com
< cpp‎ | language

  - `consteval` - specifies that a function is an immediate function, that is, every call to the function must produce a compile-time constant

### Explanation

The `consteval` specifier declares a function or function template to be an immediate function, that is, every call to the function must (directly or indirectly) produce a compile time constant expression. It may not be applied to destructors, allocation functions, or deallocation functions. A `consteval` specifier implies `inline`. The `consteval` and `constexpr` specifiers cannot both appear within the same sequence of declaration specifiers. If any declaration of a function or function template contains a `consteval` specifier, then all declarations of that function or function template must contain that specifier.

An immediate function is a constexpr function, and must satisfy the requirements applicable to constexpr functions or constexpr constructors, as the case may be.

An invocation of an immediate function whose innermost non-block scope is not a function parameter scope of an immediate function must produce a constant expression; such an invocation (known as an immediate invocation) is always evaluated, even in an unevaluated operand.

    consteval int sqr(int n) {
      return n*n;
    }
    constexpr int r = sqr(100);  // OK

    int x = 100;
    int r2 = sqr(x);  // Error: Call does not produce a constant

    consteval int sqrsqr(int n) {
      return sqr(sqr(n)); // Not a constant expression at this point, but OK
    }

    constexpr int dblsqr(int n) {
      return 2*sqr(n); // Error: Enclosing function is not consteval and sqr(n) is not a constant
    }

An identifier expression that denotes an immediate function may only appear within a subexpression of an immediate invocation or within an immediate function context. A pointer or reference to an immediate function can be taken but cannot escape constant expression evaluation:

    consteval int f() { return 42; }
    consteval auto g() { return f; }
    consteval int h(int (*p)() = g()) { return p(); }
    constexpr int r = h();   // OK
    constexpr auto e = g();  // ill-formed: a pointer to an immediate function is
                             // not a permitted result of a constant expression

### Keywords

`consteval`

### Example

| This section is incomplete Reason: no example

### See also

- `constexpr`
- constant expression

Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/language/consteval&oldid=108488"