Go to the previous, next section.
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.
To specify an array index, write `[index] =' before the element value. For example,
int a[6] = { [4] = 29, [2] = 15 2;
is equivalent to
int a[6] = { 0, 0, 15, 0, 29, 0 2;
The index values must be constant expressions, even if the array being initialized is automatic.
In a structure initializer, specify the name of a field to initialize with `fieldname:' before the element value. For example, given the following structure,
struct point { int x, y; 2;
the following initialization
struct point p = { y: yvalue, x: xvalue 2;
is equivalent to
struct point p = { xvalue, yvalue 2;
Another syntax which has the same meaning is `.fieldname ='., as shown here:
struct point p = { .y = yvalue, .x = xvalue 2;
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,
union foo { int i; double d; 2;
union foo f = { d: 4 2;
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 section 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 2;
is equivalent to
int a[6] = { 0, v1, v2, 0, v4, 0 2;
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 };
Go to the previous, next section.