What do square brackets mean in array initialization in C?

It means initialise the n-th element of the array. The example you've given will mean that:

togglecode[0x3A] == CAPSLOCK
togglecode[0x45] == NUMLOCK
togglecode[0x46] == SCROLLLOCK

These are called "designated initializers", and are actually part of the C99 standard. However, the syntax without the = is not. From that page:

An alternative syntax for this which has been obsolete since GCC 2.5 but GCC still accepts is to write [index] before the element value, with no =.


According to the GCC docs this is ISO C99 compliant. They refer to it as "Designated Initializers":

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 };

I've never seen this syntax before, but I just compiled it with gcc 4.4.5, with -Wall. It compiled successfully and gave no warnings.

As you can see from that example, it allows you to initialize specific array elements, with the others being set to their default value (0).


That was introduced in C99 and it's called a designated initialiser.

It basically allows you to set specific values in an array with the rest left as defaults.

In this particular case, the array indexes are the keyboard scan codes. 0x3a is the scan code in set #1 (see section 10.6) for the CapsLock key, 0x45 is NumLock and 0x46 is ScrollLock.

On the first link above, it states that:

int a[6] = { [4] = 29, [2] = 15 };

is equivalent to:

int a[6] = { 0, 0, 15, 0, 29, 0 };

Interestingly enough, though the link states that = is necessary, that doesn't appear to be the case here. That's not part of the standard but is a hangover from a rather old version of gcc.


It's (close to) the syntax of designated initializers, a C99 feature.

Basically, it initializes parts of an array, for example;

int aa[4] = { [2] = 3, [1] = 6 };

Intializes the second value of the array to 6, and the third to 3.

In your case the array offsets happen to be in hex (0x3a) which initializes the 58'th element of the array to the value of CAPSLOCK which presumably is defined in the code above the code you're showing.

The version in your code without the = seems to be a gcc specific extension.