简体   繁体   中英

Array assignment by index while declaration in c language

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

Does the above way of a[] array assignment is supported in c language. if yes which c version.
i compiled above code with gcc it works fine.

but i never saw this kind of assignment before.

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 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM