Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 719
Moby Disk Avatar asked Mar 25 '16 16:03

Moby Disk


1 Answers

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

like image 143
Adam B Avatar answered Oct 01 '22 11:10

Adam B