Array assignment by index while declaration in c language Array assignment by index while declaration in c language arrays arrays

Array assignment by index while declaration in c language


This is GCC extension to C89, part of standard in C99, called 'Designated initializer'.

See http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html.


Must be compiled using gcc -std=c99 or above, otherwise you get:

warning: x forbids specifying subobject to initialize

GNU C allows this as an extension in C89, to skip this warning when -pedantic flag is on you can use __extension__

void fun (){    int i;    __extension__ int a[]=    {        [0]=3,        [1]=5    };}


From the GNU C Reference Manual:

When using either ISO C99, or C89 with GNU extensions, you can initialize array elements out of order, by specifying which array indices to initialize. To do this, include the array index in brackets, and optionally the assignment operator, before the value. Here is an example:

 int my_array[5] = { [2] 5, [4] 9 };

Or, using the assignment operator:

 int my_array[5] = { [2] = 5, [4] = 9 };

Both of those examples are equivalent to:

 int my_array[5] = { 0, 0, 5, 0, 9 };