【问题标题】:Embedding a named struct as an anonymous struct in another struct将命名结构作为匿名结构嵌入到另一个结构中
【发布时间】:2016-08-04 15:46:55
【问题描述】:

下面的代码合法吗?

#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 标准。

【问题讨论】:

  • 不,这并不合法,因为带有前导下划线后跟大写字母的符号被保留用于实现(即编译器和标准库)。
  • @JoachimPileborg 好的,让我们暂时忽略这方面:)。我主要指的是BASE_STRUCT的使用方式。
  • @dxiv 仅与 struct { } 一起使用,如果该结构在其他地方声明并在此示例中按名称引用,则不会。 stackoverflow.com/questions/23527255/…
  • @arsv 你是对的,我删除了我之前的评论。 C11 中发布的代码是非法的,因为基础结构有一个标签 (_BASE_STRUCT)。如果标签被删除(留下typedef struct { ... } BASE_STRUCT;)仍然是非法的,但这是一个更好的点,C11 草案直到接近尾声才明确。请参阅 Keith Thompson 和 Johannes Schaub 在 Is this a C11 anonymous struct? 下的 cmets,了解草案 N1548 与 N1570 之间 anonymous structure 的定义略有变化。
  • Visual Studio 不符合任何 C 标准。很可能,它只是将您的代码编译为 C++,它对待结构的方式与 C 不同。

标签: c struct c11


【解决方案1】:

这是一个非标准的扩展,我认为即使在 C11 中也不行。
GCC 只接受带有 -fms-extensions 的代码

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

【讨论】:

    猜你喜欢
    • 2015-02-23
    • 2017-06-16
    • 2014-01-14
    • 1970-01-01
    • 2023-03-19
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多