user121986
user121986

Reputation: 91

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.

Upvotes: 9

Views: 3635

Answers (3)

David Ranieri
David Ranieri

Reputation: 41017

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

Upvotes: 7

devnull
devnull

Reputation: 123558

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

Upvotes: 3

nothrow
nothrow

Reputation: 16168

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.

Upvotes: 7

Related Questions