I'm implementing a constexpr int foo();
function. In the body of foo()
, I want to do something different (and possibly return something different) at compile time and something different at run-time.
With C++20, I can use std::is_constant_evaluated
:
constexpr int foo() { return std::is_constant_evaluated() ? 123 : 456 };
but what if I'm using C++17 (or earlier) - what can I do with the same effect?
Note: Compiler-specific solutions are acceptable (though less desirable).
Compile time is the period when the programming code (such as C#, Java, C, Python) is converted to the machine code (i.e. binary code). Runtime is the period of time when a program is running and generally occurs after compile time.
Some portion of the Python coding is executed at compile time, but almost all the checking like name, type and so on, are deferred until code execution. So, if the Python code references a user-defined function that hardly exists, the code will run effectively.
Compile-Time Errors: Errors that occur when you violate the rules of writing syntax are known as Compile-Time errors. This compiler error indicates something that must be fixed before the code can be compiled. All these errors are detected by the compiler and thus are known as compile-time errors.
In computing, compile-time function execution (or compile time function evaluation, or general constant expressions) is the ability of a compiler, that would normally compile a function to machine code and execute it at run time, to execute the function at compile time.
Note: Compiler-specific solutions are acceptable (though less desirable).
Let's mention the most obvious ones:
gcc
has __builtin_is_constant_evaluated()
at least documented since 9.2.0.
clang
has the same builtin since clang-9.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With