initialization of anonymous structures or unions in C1X

柔情痞子 提交于 2019-11-28 23:14:19

f and h should correctly initialize all members, as i and j are to be treated like members of struct foo (C1x 6.7.2.1 §13):

The members of an anonymous structure or union are considered to be members of the containing structure or union.

I don't think that gcc's initialization of g is correct, considering C1x 6.7.9 §9:

Except where explicitly stated otherwise, for the purposes of this subclause unnamed members of objects of structure and union type do not participate in initialization.

§20 - which deals with sub-aggregates - contains no explicit statement relevant to the issue, so my best guess would be that §9 applies (but only to the aggregate itself, not to its members!).

The bottom line is that anonymous sub-aggregates don't exist as separate objects, ie tcc's behaviour should be correct...

Example code for my take on the issue:

struct foo
{
    struct bar { int i; }; // (1) unnamed, but tagged, ie *not* anonymous
    struct { int j; };     // (2) unnamed, but anonymous
    struct { int k; } baz; // (3) named, but not tagged
};

(1) takes no part in initialization, (2) initializes as though struct foo had an additional member named j, (3) initializes as a regular sub-aggregate.

If my interpretation is correct, anonymous structures only make sense if contained within a union: an anonymous structure within a structure is indistinguishable from a flat structure containing additional members.

All members that have names in your structure can be initialized. You just can't initialize the intermediate structures as such. But

struct foo f = { .a = 1, .i = 2, .j = 3, .b = 4 };

should do it.

I haven't read the draft, I'm pretty sure unnamed and anonymous members are different. Unnamed would be something like

struct foo {
    int bar:1; /* named */
    int :31;   /* unnamed */
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!