Initializing Arrays Using Designated Initializers

C C supports designated initializers for aggregate types. A designator points out a particular array element to be initialized, and is of the form "[index]", where index is a constant expression. A designator list is a combination of one or more designators for any of the aggregate types. A designator list followed by an equal sign constitutes a designation.

In the absence of designations, initialization of an array occurs in the order indicated by the initializer. When a designation appears in an initializer, the array element indicated by the designator is initialized, and subsequent initializations proceed forward in initializer-list order, overriding any previously initialized array element, and initializing to zero any array elements that are not explicitly initialized.

The declaration syntax without a designated initializer uses braces to indicate initializer lists, but is referred to as a bracketed form. The fully bracketed and minimally bracketed forms of initialization are less likely to be misunderstood. The following are valid declarations of the multidimensional array matrix that achieve the same thing. All array elements that are not explicitly initialized, such as the entire row beginning with matrix[3][0][0], are initialized to zero.

/* minimally bracketed form */
int matrix[4][3][2] = {
    1, 0, 0, 0, 0, 0,
    2, 3, 0, 0, 0, 0,
    4, 5, 6
};
 
/* fully bracketed form */
int matrix[4] [3] [2] = {
    {
        { 1 },
    },
    {
        { 2, 3 },
    },
    {
        { 4, 5 },
        { 6 }
    }
};
 
/* incompletely but consistently bracketed initialization */
int matrix[4] [3] [2] = {
    { 1 },
    { 2, 3 },
    { 4, 5, 6 }
};
 

The overriding of previous subobject initializations during an array initialization is necessary behavior for the designated initializer. To illustrate this, a single designator is used to "allocate" space from both ends of an array. The designated initializer, [MAX-5] = 8, means that the array element at subscript MAX-5 should be initialized to the value 8. The array subscripting brackets must enclose a constant expression.

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

If MAX is 15, a[5] through a[9] will be initialized to zero. If MAX is 7, a[2] through a[4] will first have the values 5, 7, and 9, respectively, which are overridden by the values 8, 6, and 4. In other words, if MAX is 7, the initialization would be the same as if the declaration had been written:

int a[MAX] = {
      1, 3, 8, 6, 4, 2, 0
};

Related References

IBM Copyright 2003