I tried
const int i[] = { 1, 2, 3, 4 };
float f[i[3]]; // g++ cries "error: array bound is not an integer constant"
int main()
{
const int j[] = { 0, 1, 2, 3 };
float g[j[3]]; // compiler is happy :)
return 0;
}
What is the difference between the two aggregates? How come referring to a const aggregate’s element inside main() is valid when it’s invalid at the global scope?
In C++ sizes in array declaration have to be Integral Constant Expressions (ICE). By definition, ICE in C++ cannot include a value taken from an array, regardless of whether it is a
constarray or not. So, in both casesi[3]andj[3]are not ICEs and cannot be used as sizes in array declarations. For this reason both declarations –fandg– are illegal in C++.However, since you are using GCC, in the second case a non-standard compiler extension comes into play. When you are declaring an automatic array, GCC allows you to specify a non-constant size (i.e. run-time size) for the array (this is basically C99’s VLAs carried over to C++). This is why it is “happy”, even though the code is not legal in C++. Compile in
-ansi -pedantic-errormode and you should get a diagnostic message (an error) for each declaration.