When would you declare a C++20 function consteval rather than constexpr, and what does C++23's if consteval add?
answer
- must, not may
- every call is a constant
- bad input becomes a build error
- the format string check
- a branch allowed to call it
basics
~20 sUse consteval when a call must never happen at run time, such as validating a configuration or format string: every call must produce a constant, or the build fails. C++23's if consteval lets a constexpr function call it in its compile-time branch.
solid answer
~40 sA `consteval` function (C++20) is an **immediate function**: every call must itself be a constant expression, so a call with a run-time argument is a compile error, and a bad input found during evaluation, for example by reaching a `throw`, is a compile error too. That makes it the tool for compile-time validation: `parse_endpoint("port=8443;tls=1")` either yields a checked value or stops the build, and `std::format`'s format strings are checked this way through a `consteval` constructor of `std::basic_format_string`. `constexpr` is the better default when the function is also useful at run time. A plain `constexpr` function cannot call a `consteval` one with its own parameters, even inside `if (std::is_constant_evaluated())`; C++23's `if consteval { ... } else { ... }` fixes that, because its first branch is an immediate function context.
code
cpp · 25 lines#include <cstdio>
#include <string_view>
struct Endpoint { unsigned port; bool tls; };
// Parses "port=8443;tls=1" while compiling; a malformed string is a build error.
consteval Endpoint parse_endpoint(std::string_view s) {
if (!s.starts_with("port=")) throw "expected port="; // C++20 starts_with
unsigned port = 0;
std::size_t i = 5;
for (; i < s.size() && s[i] != ';'; ++i) {
if (s[i] < '0' || s[i] > '9') throw "port is not a number";
port = port * 10 + unsigned(s[i] - '0');
}
if (port == 0 || port > 65535) throw "port out of range";
return {port, s.substr(i) == ";tls=1"};
}
constexpr Endpoint kListen = parse_endpoint("port=8443;tls=1");
static_assert(kListen.port == 8443 && kListen.tls);
int main() {
std::printf("%u %d\n", kListen.port, kListen.tls);
// auto bad = parse_endpoint("port=84a3"); // error: not a constant expression
}go deeper
Recall that consteval functions must run at compile time while constexpr functions only may.
Show compile-time validation with consteval, where reaching a throw makes the build fail, and name std::format strings as a library use.
Explain why is_constant_evaluated cannot call a consteval helper with parameters and how if consteval's immediate function context fixes it.
Decide where compile-time validation pays off, such as configuration and protocol tables, against longer builds and harder-to-read compiler diagnostics.
## Immediate functions `consteval` (C++20) declares an **immediate function**. Where a `constexpr` function *may* be evaluated at compile time, a `consteval` function *must* be: every call has to be a constant expression on the spot, which the standard calls an **immediate invocation**. Consequences: - A call with a run-time argument is a compile error. Apple clang 21 reports `call to consteval function 'parse_port' is not a constant expression`, noting `read of non-constexpr variable 's' is not allowed in a constant expression`. - No code for the function is needed at run time; only its results end up in the program. - Taking its address is allowed only inside another immediate context, because a pointer to it must not escape to run time. ## Compile-time validation: a config string for a network stack The main reason to choose `consteval` is to turn bad input into a build error. A network stack parses a listener specification: ```cpp consteval Endpoint parse_endpoint(std::string_view s) { if (!s.starts_with("port=")) throw "expected port="; // ... digits, range check, ";tls=1" ... } constexpr Endpoint kListen = parse_endpoint("port=8443;tls=1"); ``` The `throw` is never meant to run. Evaluating a throw-expression is not allowed during constant evaluation through C++23, so reaching it makes the call non-constant, and an immediate invocation that is not constant is ill-formed. `parse_endpoint("port=84a3")` therefore fails to compile, and the compiler's notes point at the `throw` line, whose message string documents the problem. C++26 does allow throwing and catching during constant evaluation, as long as the exception does not escape it; an exception that escapes still makes the call non-constant, so the trick keeps working. The standard library uses the same mechanism. `std::format("{} {}", a)` does not compile, because the format string is passed as a `std::basic_format_string`, whose constructor is `consteval`, and the draft states a call to it is not a core constant expression unless the string is a valid format string for the argument types. ## Choosing between them | | `constexpr` function | `consteval` function | |---|---|---| | May run at run time | yes | no | | Run-time argument | allowed | compile error | | Good for | code shared between compile time and run time, such as CRC-32 | validation and code generation that must never run at run time | | Standard | C++11 | C++20 | Typical `consteval` candidates: - parsers for configuration, protocol descriptions or unit strings that are always written as literals; - user-defined literal operators, such as a `_ip` suffix that turns `"10.0.0.1"_ip` into a checked address or fails the build; - wrappers that validate a string against arguments, as the format string check does. Default to `constexpr`. Choose `consteval` when a run-time call would be a bug: a check that is only meaningful if it fails the build, or a computation whose run-time version would be too slow or would pull in code you do not want shipped. ## The problem if consteval solves A `constexpr` function sometimes wants to call a `consteval` helper when it is itself being evaluated at compile time. C++20's `if (std::is_constant_evaluated())` does not allow that: the call `sq(x)` with a function parameter `x` is still an immediate invocation that must be constant on its own, and it is not, so Apple clang 21 rejects it with `function parameter 'x' with unknown value cannot be used in a constant expression`. C++23 adds the **consteval if statement**: 1. `if consteval { A } else { B }` runs `A` when the enclosing evaluation is manifestly constant-evaluated, and `B` otherwise. 2. `A` is an **immediate function context**, so calls to `consteval` functions inside it are not required to be constant by themselves. 3. Both branches must be compound statements, with braces, even for one statement. 4. `if !consteval { ... }` is the negated form. The `else` branch may then call things that cannot run at compile time at all, such as I/O, intrinsics or a hardware CRC instruction, while the `consteval` branch uses a portable compile-time implementation. ## What the interviewer is checking That you know *must* versus *may*, can name a real use (compile-time validation, `std::format` strings), know that a `throw` in a `consteval` function becomes a compile error, and can explain why `if consteval` exists rather than only `std::is_constant_evaluated()`.
- Why does a throw inside a consteval function produce a compile error instead of an exception?Through C++23, evaluating a throw-expression is not allowed during constant evaluation, so a call that reaches it is not a constant expression. Every call to a `consteval` function must be one, so the program is ill-formed and the compiler points at the `throw`. C++26 permits exceptions caught within the evaluation, but one that escapes still makes the call non-constant.
- How does std::format reject a format string with too few arguments at compile time?Its first parameter is `std::format_string<Args...>`, an alias of `std::basic_format_string`, whose converting constructor is `consteval`. The standard says that call is not a constant expression unless the string is a valid format string for the argument types. A bad string therefore fails the immediate invocation and the build. Strings known only at run time go through `std::vformat`, or C++26's `std::dynamic_format`.
- consteval and constexpr functions differ only in name.
- A consteval function falls back to run time when arguments are not constant.
- A throw in a consteval function is thrown when the program starts.
- std::is_constant_evaluated() lets you call consteval functions with parameters.
- if consteval may omit braces around a single statement.
Assumes C++23 for if consteval; consteval itself is C++20, and C++26 additionally allows exceptions that are caught within constant evaluation.