I should know that, C edition
Mar 26, 2016I had drinks with friends a couple of weeks ago and I mentioned a Hacker News discussion that included a link to a thread involving Rajiv Kurian in a comment on undefined behavior1 in C (the thread isn’t itself all that interesting but Krister Walfridsson blog post on compiler optimization is). They’re more experienced and/or better with C than I am and we sipped our beers and laughed at my and at our mutual expense for not knowing some of these. I don’t write much C for work in the past several years but I do make a point to re-educate myself.
Today I was reading Bruce Dawson’s blog and one of the bug reports he filed for Chromium against the Microsoft VC[]{.underline} compiler included an array initializer construct I hadn’t seen (to some relief that I’m not a complete twit, he hadn’t either). I can’t be the only one who learned C before C99 (or before C90…) and didn’t know this syntax exists, from the GCC manual:
bq.. In ISO C99 you can give the elements in any order, specifying the array indices or structure field names they apply to, and GNU C allows this as an extension in C90 mode as well. This extension is not implemented in GNU C[]{.underline}.
To specify an array index, write ‘[index] =’ before the element value. For example,
int a[6] = { [4] = 29, [2] = 15 };
is equivalent to
int a[6] = { 0, 0, 15, 0, 29, 0 };
The index values must be constant expressions, even if the array being initialized is automatic.
and note that:
If the value in it has side-effects, the side-effects happen only once, not for each initialized field by the range initializer.
Have a sip and laugh, but I know it now.