Sun Studio 12: C User's Guide

D.1.13 Designated Initializers

6.7.8 Initialization

Designated initializers provide a mechanism for initializing sparse arrays, a practice common in numerical programming.

Designated initializers allows initialization of sparse structures, common in systems programming, and allows initialization of unions via any member, regardless of whether or not it is the first member.

Consider these examples. This first example shows how designated initializers are used to initialize an array:


 enum { first, second, third };
          const char *nm[] = {
          [third] = "third member",
          [first] = "first member",
          [second] = "second member",
          };

The following example demonstrates how designated initializers are used to initialize the fields of a struct object:


division_t result = { .quot = 2, .rem = -1 };

The following example shows how designated initializers can be used to initialize complicated structures that might otherwise be misunderstood:


 struct { int z[3], count; } w[] = { [0].z = {1}, [1].z[0] = 2 };

An array can be created from both ends by using a single designator:


int z[MAX] = {1, 3, 5, 7, 9, [MAX-5] = 8, 6, 4, 2, 0};

If MAX is greater than ten, the array will contain zero-valued elements in the middle; if MAX is less than ten, some of the values provided by the first five initializers will be overridden by the second five.

Any member of a union can be initialized:


union { int i; float f;} data = { .f = 3.2 };