in the English Wikipedia page on C++11, we can read that:
Prior to C++11, the values of variables could be used in constant expressions only if the variables are declared const, have an initializer which is a constant expression, and are of integral or enumeration type. C++11 removes the restriction that the variables must be of integral or enumeration type if they are defined with the constexpr keyword:
constexpr double earth_gravitational_acceleration = 9.8; constexpr double moon_gravitational_acceleration = earth_gravitational_acceleration / 6.0; What does it mean? In particular, does it mean that:
const double earth_gravitational_acceleration = 9.8; const double moon_gravitational_acceleration = earth_gravitational_acceleration / 6.0; is illegal in C++ prior to C++11? g++ is totally OK with this, even with -ansi, -pedantic and other...
Thanks!
23 Answers
Your second example is not at all illegal. It's just not a compile-time constant. The values may possibly be computed at runtime.
To see a difference, you need to start by using the result in some way that requires a constant expression, such as defining the size of an array. Since g++ has an extension that allows C99-style variable length arrays in C++, you probably need to make those globals as well.
So, let's consider a few possibilities:
double a = 12.34; // non-const const double b = a; // const initialized from non-const. Allowed const double b_prime = 12.34; // const initialized from literal. double constexpr c = 34.56; // constexpr instead. int x[(int)a]; // fails. `a` is not a constant expression int y[(int)b]; // fails. `b` is `const`, but not a constant expression int y_prime[(int) b_prime]; // works in g++, but shouldn't be allowed. int z[(int)c]; // works Note that constexpr is new enough that some compilers don't support it (e.g., VC++ doesn't, at least up through the version included in VS 2013).
They provided an example on the same page:
int get_five() {return 5;} int some_value[get_five() + 7]; // Create an array of 12 integers. Ill-formed C++03 constexpr int get_five() {return 5;} int some_value[get_five() + 7]; // Create an array of 12 integers. Legal C++11 Because get_five is guaranteed to be 5 at compile-time, it can be used in a constant expression.
For example this will cause an error:
constexpr int get_five() { int a = 5; return a;} 1