C11 anonymous structs via typedefs?

后端 未结 3 1329
甜味超标
甜味超标 2021-02-07 08:05

Anonymous structs have been added in the C11 standard, so

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

is valid and stand

3条回答
  •  不要未来只要你来
    2021-02-07 08:32

    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;
    }
    

提交回复
热议问题