C11 anonymous structs via typedefs?

爱⌒轻易说出口 提交于 2019-12-03 15:50:21

问题


Anonymous structs have been added in the C11 standard, so

typedef struct { 
    struct {int a, b};
    int c; 
} abc_struct;

is valid and standard. Is it also within the standard to use a typedef in place of the full struct declaration? E.g.:

typedef struct { 
    int a, b;
} ab_struct;

typedef struct { 
    ab_struct;
    int c; 
} abc_struct;

The GCC documentation says that this is a Plan 9 extension, but then it works in the few compilers I've tried (including GCC...). By my reading of the standard itself, I think it's OK, but this is the sort of close reading that's easy to screw up.


回答1:


This was apparently asked in a question to the C committee by Joseph S. Myers of the gcc team. And the answer is no, it is not valid in C11.

See the answer here:

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1549.pdf

And Myers's comment:

This week's London WG14 meeting agreed to disallow the use of typedefs in declaring anonymous structure and union fields, as per N1549.

source http://gcc.gnu.org/ml/gcc-patches/2011-03/msg01151.html

The question was asked in SC22WG15.12205 see 5.28 SC22WG14.12205, Anonymous Structures (N1425) in http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1490.pdf




回答2:


Actually your second snippet is fraught with peril and is not equivalent to the first one without explicitly specifying -fplan9-extensions in gcc.

In particular ab_struct; declaration on line 6 does NOTHING (as per gcc warning). Just pasting your second snippet in foo.c generates:

foo.c:6: warning: declaration does not declare anything

And in particular if you were to try:

typedef struct { 
    int a, b;
} ab_struct;

typedef struct { 
    ab_struct;
    int c; 
} abc_struct;


int main() {
    abc_struct abc;
    abc.a = 5;
    return 0;
}

you would get a syntax error on line 13 abc.a = 5; without the -fplan9-extensio.

whereas using the top snippet your anonymous structure will work as you are thinking it should. Namely:

typedef struct { 
    struct { 
            int a, b;
    };
        int c; 
} abc_struct;


int main() {
    abc_struct abc;
    abc.a = 5;
    return 0;
}



回答3:


Well, I'm afraid I haven't bothered to get the finished standard yet, but here's what the final draft says:

  • An unnamed member whose type specifier is a structure specifier with no tag is called an anonymous structure; an unnamed member whose type specifier is a union specifier with no tag is called an anonymous union.

I can only interpret the as that only struct {}; and union {}; can be an anonymous struct/union.



来源:https://stackoverflow.com/questions/9142163/c11-anonymous-structs-via-typedefs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!