I have read about constexpr
in C++17 using this reference link.
Then, I made C++ program to test constexpr
:
#include <iostream>
int i = 10;
int func()
{
if constexpr (i == 0)
return 0;
else if (i > 0)
return i;
else
return -1;
}
int main()
{
int ret = func();
std::cout<<"Ret : "<<ret<<std::endl;
}
But, compiler give an error:
main.cpp: In function 'int func()':
main.cpp:8:25: error: the value of 'i' is not usable in a constant expression
if constexpr (i == 0)
^
main.cpp:4:5: note: 'int i' is not const
int i = 10;
Why gives an error?
You misunderstood the meaning of
if constexpr
. This is not a test for const expression to be performed at runtime, it is a test of a logical expression to be performed at compile time.The construct is roughly similar to
#if
of preprocessor, in that the other branch is eliminated, along with code that may otherwise not compile.This will work:
The compiler knows the value of
i
at compile time, so depending on its value only one of the three branches is going to remain in the compiled code.