Reputation: 11
In the following code why is that the two statements are illegal
const int i[] = { 1, 2, 3, 4 };
// float f[i[3]]; // Illegal
struct S { int i, j; };
const S s[] = { { 1, 2 }, { 3, 4 } };
//double d[s[1].j]; // Illegal
int main() {}
Why are they illegal? The textual definition is as follows which i didn't understand.
"In an array definition, the compiler must be able to generate code that moves the stack pointer to accommodate the array. In both of the illegal definitions above, the compiler complains because it cannot find a constant expression in the array definition."
Thanks in advance.
Upvotes: 0
Views: 156
Reputation: 12885
because d is static array, that means that it's size has to be know at compilation time. Therefore you can't use non-const variables as size parameter.
But you can try
const int i = 3;
double d[i];
for example.
Upvotes: 0
Reputation: 477388
Array sized need to be constant expressions. Try this:
constexpr int i[] = { 1, 2, 3, 4 };
float f[i[3]];
The constexpr
keyword was introduced in C++11. Previous versions of C++ had no concept of such general constant expressions, and there was no equivalent concept.
Upvotes: 6
Reputation: 258618
Because C++ doesn't support variable-length arrays, and s[1].j
is not a compile-time constant.
What that quote refers to is the fact that f
and d
are in automatic storage. The run-time will clean their memory automatically when they go out of scope. As such, it must know the size beforehand.
Upvotes: 2