The following code fails to compile live on Ideone:
#include <iostream>
using namespace std;
int main() {
const double kPi = 3.14;
constexpr double kPi2 = 2.0*kPi;
cout << kPi2;
}
The error message is:
prog.cpp: In function 'int main()': prog.cpp:6:30: error: the value of 'kPi' is not usable in a constant expression constexpr double kPi2 = 2.0*kPi; ^ prog.cpp:5:15: note: 'kPi' was not declared 'constexpr' const double kPi = 3.14;
Substituting the const
declaration for kPi
with constexpr
, it compiles successfully.
On the other hand, when int
is used instead of double
, seems like const
plays well with constexpr
:
#include <iostream>
using namespace std;
int main() {
const int k1 = 10;
constexpr int k2 = 2*k1;
cout << k2 << '\n';
return 0;
}
Why do int
and double
get different treatments for initializing a constexpr
with const
?
Is this a bug in the Ideone compiler? Is this required by the C++ standard? Why is that?
Was the above code UB?
P.S. I tried with Visual Studio 2015 C++ compiler, and it compiles the first code snippet (initializing constexpr
with const
) just fine.
Rule:"constexpr must be evaluate at compile time".
Let's look below code (generic example);
k1 is constant, the value of its initializer is not known compile time but its initializer is known until run time so k1 is not constant expression. As a result a const variable is not constexpr.
But compiler see these code:
One exception occurs. A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations [1].
You can get extra information from the links below:
constexpr
andconst
| stackoverflow