sách gpt4 ăn đã đi

c - union 内的无名 union

In lại 作者:太空狗 更新时间:2023-10-29 16:40:52 27 4
mua khóa gpt4 giày nike

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

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

从语法上看,可以去掉内层 union 体{},在外层 union 体{}中直接拥有*a、*b、*c。那么无名嵌入式 union 的目的是什么?

câu trả lời hay nhất

另一个 union/结构内的未命名 union/结构是 C11 和一些编译器扩展(例如 GCC)的一个特性。

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.

此功能的优点是可以更轻松地访问其未命名的 union 字段:

type_t x;

要访问字段Một,您可以简单地使用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;

你需要使用x.u.a

相关:unnamed struct/union in C

关于c - union 内的无名 union ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22406229/

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress