The following code is fine:
constexpr double square_cstxpr(double x) { return x * x; }
int main() {
const int test = 5;
constexpr double result = square_cstxpr((double)test);
}
However, if the type of test
is changed from const int
to const double
, g++ gives the following error: the value of 'test' is not usable in a constant expression
.
See the code and output of g++ here: http://coliru.stacked-crooked.com/a/2fe9b176c2b23798
Could somebody explain that behavior?
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.
A constant variable is one whose value cannot be updated or altered anywhere in your program. A constant variable must be initialized at its declaration. To declare a constant variable in C++, the keyword const is written before the variable's data type.
A constant expression is an expression that can be evaluated at compile time. Constants of integral or enumerated type are required in several different situations, such as array bounds, enumerator values, and case labels. Null pointer constants are a special case of integral constants.
Understanding Constants A constant is a data item whose value cannot change during the program's execution.
Non-constexpr
but const
variables must be of integer or enumeration type for them to be usable in constant expressions. See [expr.const]/2:
an lvalue-to-rvalue conversion unless it is applied to
(2.7.1) a non-volatile glvalue of integral or enumeration type that refers to a complete non-volatile const object with a preceding initialization, initialized with a constant expression, or [..]
The reasons for this limitation must be mostly historical. Floating points have been handled with care when it comes to constant expressions; think non-type template parameters. This is due to their strongly platform dependent behaviour that renders compile time calculations less mathematical than they should be.
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