When we initialize an array like this int a[5] = {0}
, the compiler makes all 5 elements 0. That is really good, compact-initialization and useful feature.
But I wonder why the compiler doesn't initialize int a[5]={1}
similarly? Why does it not make all 5 elements 1? Why the Standard doesn't mandate it? Would it not been an awesome feature? Isn't it missing?
Also, if the number of elements in the initializer is less than the size of the array, then the compile could initialize the remaining elements with the last element in the initializer. Means, int a[5]={1,2,3}
is equivalent to int a[5]={1,2,3,3,3}
. And similarly, int a[10]={1,2,3,0}
is equivalent to int a[10]={1,2,3,0,0,0,0,0,0,0};
.
Would it all not be an awesome feature if the Standard mandates it? Or is there any good reasons for this missing feature?
And there is something called designated initializer in C99, which is used like:
Designated initializers can be combined with regular initializers, as in the following example:
int a[10] = {2, 4, [8]=9, 10}
In this example, a[0] is initialized to 2, a1 is initialized to 4, a[2] to a[7] are initialized to 0, and a[9] is initialized to 10.
Quite interesting. But even this feature is not in C++.