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

282 views Asked by At

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?

2

There are 2 answers

0
Sourav Ghosh On BEST ANSWER

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. [...]

0
haccks On

Is it correct output of index 8 and 9 without explicitly defined it?

Yes, it is correct. Compiler will initialize elements of array after index 7.
The initializer initializes the first three elements to 1, 2 and 3. Element at index 7 will have the value 4. The two elements after index 7 will have values 8 and 9 respectively.

Why sequence does not start from index 3?

Designated initializer [7] tells the compiler to continue the initialization of array elements after index 7.