8

I am reading Bruce Dawson's article on porting Chromium to VC 2015, and he encountered some C code that I don't understand.

The code is:

char c[2] = { [1] = 7 };

Bruce's only comment on it is: "I am not familiar with the array initialization syntax used - I assume it is some C-only construct." So what does this syntax actually mean?

alk
  • 69,737
  • 10
  • 105
  • 255
Moby Disk
  • 3,761
  • 1
  • 19
  • 38

2 Answers2

12

C99 allows you to specify the elements of the array in any order (this appears to be called "Designated Initializers" if you're searching for it). So this construct is assigning 7 to the second element of c.

This expression is equivalent to char c[2] = {0, 7}; which does not save space for such a short initializer but is very helpful for larger sparse arrays.

See this page for more information: https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html

Adam B
  • 3,775
  • 3
  • 32
  • 42
  • 2
    It's equivalent to `char c[2] = {0, 7};` here but designated initializer is very convenient in the cases long arrays and structures. – P.P Mar 25 '16 at 16:50
  • That is another easy way to visualize, it. Added to the answer. – Adam B Mar 25 '16 at 17:04
2

Its meaning would be

char c[2]={ 0, 7 }

OR you can say

char c[2];
c[0]=0;
c[1]=7;
Mukesh
  • 83
  • 6