Is this syntax - [x] = ‘y’ in an array literal - standard C?

Viewed 63
const char Table[256] = {
     ['a'] = 'a', ['A'] = 'a',
     ['b'] = 'b', ['B'] = 'b',
     ['c'] = 'c', ['C'] = 'c',
     ['d'] = 'd', ['D'] = 'd',
     ['e'] = 'e', ['E'] = 'e',
     ['f'] = 'f', ['f'] = 'f',
     ['g'] = 'g', ['g'] = 'g',
     ['h'] = 'h', ['H'] = 'h',
     ['i'] = 'i', ['I'] = 'i',
     ['j'] = 'j', ['J'] = 'j',
     /* Etc */
};

I have seen something like that in an answer to a C question. Is this Lua-like syntax standard C, or is it some compiler extension?

1 Answers

Yes, that syntax is standard since the C99 (the 1999 ISO C standard).

It's described in the C standard: https://port70.net/~nsz/c/c11/n1570.html#6.7.9

(The link is to an HTML version of the N1570 draft, which is very close to the published 2011 edition.)

Designated initializers can also be used for struct and union members, with the syntax .name = value rather than [index] = value.

Designated initializers can also be used in compound literals: https://port70.net/~nsz/c/c11/n1570.html#6.5.2.5

Related