const-vs-constexpr-on-variables
What the guy says about constexpr is right if double
is used (or float
of course). However, if you change the var type from double
to an integer type like int, char, etc, everything works. Why does that happen?
int main()
{
const int PI1 = 3;
constexpr int PI2 = 3;
constexpr int PI3 = PI1; // works
static_assert(PI1 == 3, ""); // works
const double PI1__ = 3.0;
constexpr double PI2__ = 3.0;
constexpr double PI3__ = PI1__; // error
static_assert(PI1__ == 3.0, ""); // error
return 0;
}
Update
: the following line was a mistake, I meant PI3__ = PI1__
constexpr double PI3__ = PI1; // I meant PI1__
Questions:
Why const int = 3
is compile time constant but const double = 3.0
is not?
Is there any reason why I should use constexpr const int val;
over constexpr int val
? They both seem to do exactly the same.
From the comments it seems like OP is asking for Standard quote which defines const int
as a compile-time constant, but const double
as not.
The corresponding details are found in 5.19, Constant Expressions
. In particular:
...an lvalue-to-rvalue conversion (4.1) unless it is applied to a non-volatile glvalue of integral or enumeration type that refers to a non-volatile const object with a preceding initialization, initialized with a constant expression...
int
is an integral type, while double
is not.