Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The value of a const variable is or is not usable in a constant expression, depending on the variable type

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?

like image 929
Georg Avatar asked Aug 09 '17 14:08

Georg


People also ask

What does const do to a variable?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.

What does const variable mean?

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.

What is a constant expression?

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.

Does a constant change values during runtime?

Understanding Constants A constant is a data item whose value cannot change during the program's execution.


1 Answers

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.

like image 71
Columbo Avatar answered Oct 25 '22 12:10

Columbo