将命名结构作为匿名结构嵌入另一个结构中

时间:2016-08-04 15:46:56

标签: c struct c11

以下代码是否合法C?

#include <stdio.h>

typedef struct _BASE_STRUCT
{
    int BaseMember;
} BASE_STRUCT, *PBASE_STRUCT;

typedef struct _DERIVED_STRUCT
{
    BASE_STRUCT;    // Members belonging to this struct are "embedded" here.
    int DerivedMember;
} DERIVED_STRUCT, *PDERIVED_STRUCT;

//
// Above struct declaration is equivalent to the following, which I believe is valid
// in C11 (anonymous structs).
//
// typedef struct _DERIVED_STRUCT
// {
//     struct
//     {
//         int BaseMember;
//     };
//     int DerivedMember;
// } DERIVED_STRUCT, *PDERIVED_STRUCT;
//

int main()
{
    DERIVED_STRUCT ds;
    ds.BaseMember = 10;     // Can be accessed without additional indirection.
    ds.DerivedMember = 20;

    printf("%d\n", ds.BaseMember);

    return 0;
}

Visual Studio似乎没有抱怨它,除了有关匿名结构的警告。但是,对于使用匿名结构的代码,它具有相同的警告,因此我认为它尚未更新为符合C11标准。

1 个答案:

答案 0 :(得分:0)

这是一个非标准的延伸,我认为即使在C11也没有 GCC只接受带有-fms-extensions

的代码

https://gcc.gnu.org/onlinedocs/gcc/Unnamed-Fields.html