工会内的无名工会 [英] Nameless union inside a union

查看:34
本文介绍了工会内的无名工会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm reading some code and found something like the following:

typedef union {
    int int32;
    int boolean;
    time_t date;
    char *string;
    union {
        struct foo *a;
        struct foo *b;
        struct foo *c;
    };
} type_t;

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

From syntax point of view, the inner union {} can be removed and having *a, *b and *c directly inside the outer union {}. So what's the purpose the namelessly embedded union?

推荐答案

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

Unnamed union/struct inside another union/struct is a feature of C11, and some compiler extensions (e.g, GCC).

13 一个未命名的成员,其类型说明符是一个没有标签的结构说明符,称为匿名结构;类型说明符是没有标记的联合说明符的未命名成员称为匿名联合.匿名结构或联合的成员被认为是包含结构或联合的成员.如果包含的结构或联合也是匿名的,这将递归地适用.

C11 §6.7.2.1 Structure and union specifiers

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;

要访问字段a,您只需使用x.a.与不使用此功能的代码对比:

To access the field a, you can simply use x.a. Compare with the code without using this feature:

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;

您需要使用x.u.a.

相关:C 中未命名的结构体/联合

这篇关于工会内的无名工会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆