gpt4 book ai didi

我们可以使用 union 进行类型转换吗?

转载 作者:太空宇宙 更新时间:2023-11-04 01:21:00 25 4
gpt4 key购买 nike

考虑以下 union :

union{
uint32_t a;
uint64_t b;
};

ab 都在同一个内存区域。如果我们将 32 位整数 a 初始化为某个值,如何获得 b(当 b 未初始化时)?是不是意味着编译器在内部将a转换为b

谢谢

最佳答案

uint64_t 中的额外字节将具有未指定的值。

来自 C standard 的第 6.2.6.1 节:

7 When a value is stored in a member of an object of union type, the bytes of the object representation that do not correspond to that member but do correspond to other members take unspecified values.

以及第 6.5.2.3 节:

3 A postfix expression followed by the . operator and an identifier designates a member of a structure or union object. The value is that of the named member, 95) and is an lvalue if the first expression is an lvalue. If the first expression has qualified type, the result has the so-qualified version of the type of the designated member

95) If the member used to read the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called "type punning"). This might be a trap representation.

唯一允许的情况是您有一个或多个结构的 union ,并且每个结构都有一个相同类型的初始成员。

来自 6.5.2.3 节:

6 One special guarantee is made in order to simplify the use of unions: if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the completed type of the union is visible. Two structures share a common initial sequence if corresponding members have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.

这是一个可能有用的示例:

union sockadddr_u {
struct sockaddr sa;
struct sockaddr_un sun;
struct sockaddr_in sin;
}

这些结构存储了不同类型套接字的信息。大多数成员不同,但每个成员的第一个成员都是 sa_family_t 类型,整个值告诉您套接字类型。这允许您检查任何这些成员的第一个成员,以确定哪些成员包含其内部成员的有意义的数据。

关于我们可以使用 union 进行类型转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42441726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com