21

What is the meaning of following Code? Code is from the regression test suite of GCC.

static char * name[] = {
   [0x80000000]  = "bar"
};
0

3 Answers 3

29

In C99 you can specify the array indices to assigned value, For example:

static char * name[] = {
   [3]  = "bar"  
};

is same as:

static char * name[] = { NULL, NULL, NULL, "bar"};

The size of array is four. Check an example code working at ideaone. In your code array size is 0x80000001 (its an hexadecimal number).
Note: Uninitialized elements initialized with 0.

5.20 Designated Initializers:

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 C89 mode as well. This extension is not implemented in GNU C++. 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 };

One more interesting declaration is possible in a GNU extension:

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

To initialize a range of elements to the same value, write [first ... last] = value. For example,

 int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 }; 

Note: that the length of the array is the highest value specified plus one.

Additionally, we can combine this technique of naming elements with ordinary C initialization of successive elements. Each initializer element that does not have a designator applies to the next consecutive element of the array or structure. For example:

 int a[6] = { [1] = v1, v2, [4] = v4 };

is equivalent to

 int a[6] = { 0, v1, v2, 0, v4, 0 };

Labeling the elements of an array initializer is especially useful when the indices are characters or belong to an enum type. For example:

 int whitespace[256]  = { [' '] = 1,  ['\t'] = 1, ['\h'] = 1,
                          ['\f'] = 1, ['\n'] = 1, ['\r'] = 1 
                        };
Sign up to request clarification or add additional context in comments.

2 Comments

In your first example, [3] = "bar"; - does that really set the third element (as you have shown) or index 3 (the fourth element) as would seem more natural?
@Vicky forth element, [3] = "bar" mean 3rd index, Check this working code
9

It's called designated initializer which is introduced in C99, gcc also supports it in GNU89 as an extension, see here for detail.

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

is equivalent to

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

Comments

6

It's a C99 designated initializer. the value in brackets specifies the index to receive the value.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.