GCC gives no error when you initialize a variable-sized array as long as the variable is const, but when it isn't, it won't compile.
What's the reason behind this? What's so wrong with doing:
int size = 7;
int test[size] = {3, 4, 5};
That won't compile at all, but if I don't initialize test[] then it does compile! That doesn't make any sense to me, because as far as I know a stack frame needs to be made to fit this array according to its size(7 ints) no matter what(which means the integer literals I use don't really have any meaning, if I'm not mistaken), so what difference does it make if I initialize it or not?
Just another one of my crazy C++ design questions...
Thanks!
int arr[5];
) A constant integral variable initialized with a constant expression is a constant expression. (const int j = 4; const int i = j; int a[i];
)
A constant variable initialized with a non-constant expression is not a constant expression
int x = 4; // x isn't constant expression because it is not const
const int y = x; //therefore y is not either
int arr[y]; //error)
It's actually more like a crazy C99 design question, since variable-length arrays are a feature from C99 that gcc allows in C++ as an extension.
In C99, 6.7.8/3 says "The type of the entity to be initialized ... is not a variable length array type", so gcc has just used the same rule for its extension as is required by C99.
The C99 rationale document doesn't say anything about why a VLA can't be initialized. I can speculate that it might be because of the risk of excess elements in the initializer, if the value provided for the size turns out to be smaller than the initializer. But I don't know.
Some compilers allow this if you use const int size = 7;
. Theoretically the compiler could figure out that it's constant size but it doesn't do that.
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