同类型工会成员

Union members of the same type

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

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

如果我写到a,传值给函数,函数从b读取,期望得到a值,会不会有什么问题,考虑到 ab 具有相同的类型?成员读取是否需要完全反映成员写入?

是的,没关系。

标准(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 是非常安全的。 :)