Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do square brackets mean in array initialization in C?

Tags:

arrays

c

static uint8_t togglecode[256] = {     [0x3A] CAPSLOCK,     [0x45] NUMLOCK,     [0x46] SCROLLLOCK }; 

What's the meaning of [0x3A] here? I have only learned statements like int a[2] = {1, 2};

like image 740
akirast Avatar asked Mar 24 '12 06:03

akirast


People also ask

Why square brackets are used in array?

Square brackets are used to index (access) elements in arrays and also Strings. Specifically lost[i] will evaluate to the ith item in the array named lost.

What does square brackets mean in C?

A postfix expression (operand followed by the operator) followed by an expression in square brackets [ ] is a subscripted designation of the array element . The definition of the array subscript operator [ ] is that if a is an array and i is an integer then a[i] =*(a+i) .

What are square brackets called in array?

Putting the element index in parentheses (or brackets in this case) after an array is called “subscripting”. The index is called a “subscript”. There is no special name for directly subscripting the array returned by a message without storing the array in a variable first.

What does brackets mean in arrays?

now in your case you have an array of array's so the first(or outside) curly brackets are for defining each row and the curly brackets within them is to define each row's values inside them.


2 Answers

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 =.

like image 138
huon Avatar answered Oct 03 '22 13:10

huon


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).

like image 45
Jonathon Reinhart Avatar answered Oct 03 '22 13:10

Jonathon Reinhart