Search code examples
carraysinitializationinitializer-listdesignated-initializer

Are the elements present after a designator initializes elements in strictly increasing manner?


Here, I have initialized array like this :

#include <stdio.h>

int main() 
{
    int a[10] = {1, 2, 3, [7] = 4, 8, 9};

    printf("a[7] = %d\na[8] = %d\na[9] = %d\n", a[7], a[8], a[9]);

    return 0;
}

Output :

a[7] = 4
a[8] = 8
a[9] = 9

Here, I have selected array index 7 as a a[7] = 4 and thereafter added some elements. Then print array elements of index 7, 8 and 9 and print correctly.

So, Is it correct output of index 8 and 9 without explicitly defined it? Why sequence does not start from index 3?


Solution

  • Why sequence does not start from index 3?

    because, that's not how it works!!

    Quoting C11, chapter §6.7.9 for designated initializer (emphasis mine)

    Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.148) . In contrast, a designation causes the following initializer to begin initialization of the subobject described by the designator. Initialization then continues forward in order, beginning with the next subobject after that described by the designator.149)

    Thus, in your case, after the designator [7], the remaining two elements in the brace enclosed list will be used to initialize the next sub-objects, array elements in index 8 and 9.

    Just to add a little more relevant info,

    If a designator has the form

    [ constant-expression ]
    

    then the current object (defined below) shall have array type and the expression shall be an integer constant expression. [...]