Home > Back-end >  Why isn't constexpr guaranteed to run during compilation?
Why isn't constexpr guaranteed to run during compilation?

Time:03-31

Why isn't constexpr guaranteed to run during compilation?

Additionally, why was consteval added instead of changing constexpr to guarantee a compile-time execution?

CodePudding user response:

constexpr already guarantees compile-time evaluation when used on a variable.

If used on a function it is not supposed to enforce compile-time evaluation since you want most functions to be usable at both compile-time and runtime.

consteval allows forcing functions to not be usable at runtime. But that is not all that common of a requirement.

CodePudding user response:

The language has specific linguistic restrictions that require certain expressions to be compile-time constant expressions. Template parameters, array sizes, and a few other locations specifically require a compile-time constant value. As such, if you apply constexpr to a variable, you did so with the explicit intention of using that variable in one of those places. So the language requires that it be a constant expression.

This is not the case for functions. There are (at present in C ) few language constructs in C that a function could use at compile time which are not also available to the compiled executable at runtime. That is, there isn't much a function could do at compile time which it could not also do at runtime.

If all of a compile-time function would execute just fine with runtime values, then there's no reason to require that functions which can run at compile-time must run at compile-time.

consteval was added to the language for the specific purpose of cases where only the compiler has certain information. As it stands, there is exactly one standard library function is consteval: std::source_location::current. This is because the information being queried (the location in source code of the function call) is only available to the compiler.

  • Related