Contents|Index|Previous|Next
 Labeled elements in initializers   

Standard C requires the elements of an initializer to appear in a fixed order, the same as the order of the elements in the array or structure being initialized. In GNU C you can give the elements in any order, specifying the array indices or structure field names they apply to. This extension is not implemented in GNU C++. To specify an array index, write ‘[index]’ or ‘[index]=’ before the element value. Use the following example. The previous specification is equivalent to the following. The index values must be constant expressions, even if the array being initialized is automatic. To initialize a range of elements to the same value, write ‘[ first... last]=value’. Use the following example. In a structure initializer, specify the name of a field to initialize with ‘fieldname:’ before the element value. For example given struct point { int x, y; };, the initialization, struct point p = { y: yvalue, x: xvalue }; is equivalent to: point p = { xvalue, yvalue struct };.

Another syntax which has the same meaning is ‘.fieldname=’ as in the following statement.

You can also use an element label (with either the colon syntax or the period-equal syntax) when initializing a union, to specify which element of the union should be used. For example, the following will convert 4 to a double to store it in the union using the second element. By contrast, casting 4 to type union foo would store it into the union as the integer ‘i’, since it is an integer. (See Cast to a union type.)

You can combine this technique of naming elements with ordinary C initialization of successive elements. Each initializer element that does not have a label 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, as in the following example.


Top|Contents|Index|Previous|Next