gpt4 book ai didi

c - 同类型 union 成员

转载 作者:太空狗 更新时间:2023-10-29 15:03:34 28 4
gpt4 key购买 nike

假设我有一个 union u,其中有两个相同类型(例如 int)的成员 ab

union u{
int a,b;
char c;
};

如果我写入a,按值将它传递给函数,函数从b读取,期望得到a值,考虑到 ab 具有相同的类型,会有任何问题吗?成员读取是否需要完全反射(reflect)成员写入?

最佳答案

是的,没关系。

标准(C11 草案)说:

[...] 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

这里的两个整数可以被认为是(非常简单的)结构,它们共享相同的初始序列。

即使忽略它,还有:

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

int 重新解释为 int 是非常安全的。 :)

关于c - 同类型 union 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40256870/

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