Search code examples
carraysinitializer

What does char c[2] = { [1] = 7 }; do?


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?


Solution

  • 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