开发者

What is the meaning of a struct inside another without a tag name?

I just came across a code snippet say:-

struct a {
    int mem1;
    char mem2;

    struct {
        int inner_mem1;
        int inner_mem2;
    };
};

And I found that the code snippet using the inner struct's members direc开发者_如何转开发tly using the outer struct's variable name!!! ex:

struct a *avar;
....
avar->inner_mem1

Is this legal, the code is compiling however and working fine!. What is the purpose to use it in this way? Any specific scenarios ?

Please let me know your thoughts.


This is called an "anonymous structure":

An unnamed member of structure type with no tag is called an anonymous structure; an unnamed member of union type with no tag is called an anonymous union. The members of an anonymous structure or union are considered to be members of the containing structure or union. This applies recursively if the containing structure or union is also anonymous.

This is not part of the current C standard, C99, but it is foreseen to be part of the upcoming one (citation above). Also, many compilers already support this feature as an extension.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜