Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I initialize a variable-sized array?

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!

like image 867
Lockhead Avatar asked Jul 09 '11 13:07

Lockhead


3 Answers

  • The size of the array must be a constant integral expression.
  • An integral literal is a constant integral expression. (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)
    
like image 80
Armen Tsirunyan Avatar answered Sep 18 '22 14:09

Armen Tsirunyan


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.

like image 40
Steve Jessop Avatar answered Sep 22 '22 14:09

Steve Jessop


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.

like image 23
Karoly Horvath Avatar answered Sep 20 '22 14:09

Karoly Horvath