I'm new with c++ and currently came across with constexpr
. As I realize constexpr
functions are evaluated at compile time. Here is my source code:
constexpr int sum(float a, int b)
{
return a + b;
};
int main(int argc, char *argv[])
{
std::cout << sum(1, 2) << std::endl;
}
It is a simple function which just sums to integers. The problem is that when I set breakpoint at return a + b
and start debugging, the breakpoint is hit, which means that the function was not evaluated at compile time. But when I change main function to this:
int main(int argc, char *argv[])
{
constexpr int var = sum(2, 2);
std::cout << var << std::endl;
}
the breakpoint is not hit, which means that function was evaluated at compile time. I'm little confused why function is not evaluated in first case?
P.S I'm using visual studio 2017.
A constexpr function that is eligible to be evaluated at compile-time will only be evaluated at compile-time if the return value is used where a constant expression is required. Otherwise, compile-time evaluation is not guaranteed.
Quick A: constexpr guarantees compile-time evaluation is possible if operating on a compile-time value, and that compile-time evaluation will happen if a compile-time result is needed.
The keyword constexpr was introduced in C++11 and improved in C++14. It means constant expression. Like const , it can be applied to variables: A compiler error is raised when any code attempts to modify the value. Unlike const , constexpr can also be applied to functions and class constructors.
As I realize constexpr functions are evaluated at compile time
Not really. They can be evaluated at compile-time, but they are not guaranteed to do so, unless they're invoked in a context where a constant expression is required.
One such context is the declaration of a constexpr
variable.
constexpr
means "can be evaluated at compile time" rather than "must be evaluated at compile time". If you want to see it evaluated at compile time you can call it in a context that requires to be evaluated at compile time, for example a template parameter:
std::array<int, sum(3,5)> x;
Note that the motivation for constexpr
is the other way around than many would expect. constexpr
tells the compiler that you can use it eg as template parameter and if sum
was not constexpr
you'd get a compiler error. It is not to make sure that the function always is evaluated at compile time.
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