Designated initialization warns if struct members are not in declaration order

Hello list,

§6.7.8/17 of ISO/IEC 9899:1999 says:

"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. 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."

However, clang seems to expect the structure members to be initialized in declaration order. Hence, the following test program will issue warnings:

--------8<--------
static int
test_funca(int *a)
{
         return *a;
}

static int
test_funcb(char *b)
{
         *b = 'a';

         return 1;
}

struct test_ops {
         int (*test_a)(int *);
         int (*test_b)(char *);
};

struct test_ops test = {
         .test_b = test_funcb,
         .test_a = test_funca
};

int
main(void)
{
         return 0;
}
-------->8--------

Swapping .test_b and .test_a in the initialization will silence the warnings.

Regards,
Sascha

Designators currently get ignored by the parser. There's been some
discussion of how to implement it; unfortunately, it ends up being
relatively complicated, and nobody has gotten around to it.

It would probably be a good idea to add a warning as an interim measure, though.

-Eli

Yes, we should add this soon, its pretty bad and confusing. I would actually prefer an error to a warning, since I would much rather deal with complaints about clang not working than complaints about hard to find miscompilations.

Does anyone object to an error on designated initializers until it gets implemented?

  • Daniel

The problem with this is that it will break code that doesn't really care, such as the static analyzer and rewriter. I'd be fine with codegen producing an error on this though. This would require adding a tiny bit of tracking to know when a designator was used though.

-Chris

Although I can’t say I’m fond of adding options for this particular behavior, how bad would it be to put a bit in LangOptions saying “dont support designated initializers” and only set this bit for IR generation. This would prevent the user from seeing unrelated errors due to the misanalysis of designated initializers, i.e. excess elements warnings and be simpler to add (and remove).

  • Daniel