On 9/2/19 5:44 AM, Juha Nieminen wrote:
> In C you can use designated initializers to initialize a struct
> (or an array). There is no requirement for the order in which
> the initializers are listed, so it's completely ok to list them
> in a different order than they are declared in the struct.
> So you can have:
>
> struct S { int a, b; };
> struct S s = { .b = 1, .a = 2 };
>
> In C++20, however, you cannot list the initializers in the "wrong"
> order.
...
> I don't know what the C standard says about what happens when designated
> initializers are not in the same order as in the declaration of the struct,
I can't answer your other questions, but I can answer that one. This is
no such restriction in C on the order in which designators are written,
and here's what C2011 says about the order in which the resulting
initializations occur:
"... 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. 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." (6.7.8p17).
Thus, a designation causes a jump in the initialization order, after
which initialization moves forward as normal from the new position. You
could, as a result, end up initializing the same element or an array, or
the same member of a struct, multiple times. I would expect to see such
code only in the obfuscated C contest or in machine generated code, but
it is permitted.