工会内无名的联盟

lan*_*ng2 12 c unions

我正在阅读一些代码,发现如下内容:

typedef union {
    int int32;
    int boolean;
    time_t date;
    char *string;
    union {
        struct foo *a;
        struct foo *b;
        struct foo *c;
    };
} type_t;
Run Code Online (Sandbox Code Playgroud)

从语法的角度来看,内部联合{}可以被移除并且在外部联合{}内直接具有*a,*b和*c.那无名嵌入式联盟的目的是什么?

Yu *_*Hao 9

另一个union/struct中未命名的union/struct是C11的一个特性,以及一些编译器扩展(例如,GCC).

C11§6.7.2.1结构和联合说明符

13 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. 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.

The advantage of this feature is that one can access its unnamed union field easier:

type_t x;
Run Code Online (Sandbox Code Playgroud)

To access the field a,您只需使用即可x.a.与代码比较而不使用此功能:

typedef union {
    int int32;
    int boolean;
    time_t date;
    char *string;
    union u{      //difference in here
    struct foo *a;
    struct foo *b;
    struct foo *c;
    };
} type_t;

type_t x;
Run Code Online (Sandbox Code Playgroud)

你需要使用x.u.a.

相关:C中未命名的struct/union

  • 但这不是删除内部联盟吗?我的意思是,所有成员到底都有相同的地址,对吧? (3认同)
  • @ lang2不,它不是一回事,因为ab和c将共享相同的内存空间.如果你完全删除联盟,他们将各自获得自己的内存. (2认同)

Emm*_*met 7

我认为预期的用例更像是" 结构中的匿名联合",并且"联盟内部的匿名联合"与"扁平"联合相同的行为只是一致性的可接受的折衷.


Sco*_*ter 0

允许同一个指针被称为 a、b 或 c。也许有一些遗留代码无法就使用什么名称达成一致。

  • 但它已经在工会内部了。所以内部union结构是多余的。 (3认同)
  • 根据于浩的回答,它似乎是_modern_(C11)代码而不是_legacy_代码。 (2认同)