Assigning an array by index when declaring in c

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

Is the above method of assigning an array [] in c supported. if so, version c.
I compiled the above code with gcc, it works fine.

but I had never seen such an appointment before.

+4
source share
3 answers

This is the GCC extension for C89, part of the standard for C99, called "Assigned Initializer".

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

+5
source

You must compile with gcc -std=c99 or higher, otherwise you will get:

 warning: x forbids specifying subobject to initialize 

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

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

In the GNU C Reference Guide :

When using either ISO C99 or C89 with GNU extensions, you can initialize array elements out of order by indicating which array indices are initialized. 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 these examples are equivalent:

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

Source: https://habr.com/ru/post/1492915/


All Articles