Why does the array a not get initialized by global variable size?
#include<stdio.h>
int size = 5;
int main()
{
int a[size] = {1, 2, 3, 4, 5};
printf("%d", a[0]);
return 0;
}
The compilation error is shown as
variable-sized object may not be initialized
According to me, the array should get initialized by size.
And what would be the answer if I insist on using global variable (if it is possible)?
In C99, 6.7.8/3:
6.6/2:
6.6/6:
6.7.5.2/4:
ahas variable length array type, becausesizeis not an integer constant expression. Thus, it cannot have an initializer list.In C90, there are no VLAs, so the code is illegal for that reason.
In C++ there are also no VLAs, but you could make
sizeaconst int. That’s because in C++ you can useconst intvariables in ICEs. In C you can’t.Presumably you didn’t intend
ato have variable length, so what you need is:If you actually did intend
ato have variable length, I suppose you could do something like this:Or maybe:
It’s difficult to say, though, what “should” happen here in the case where size != 5. It doesn’t really make sense to specify a fixed-size initial value for a variable-length array.