gpt4 book ai didi

c - 类型双关与联盟成员访问

转载 作者:太空狗 更新时间:2023-10-29 16:07:47 26 4
gpt4 key购买 nike

根据这个https://stackoverflow.com/a/1812932/1814023 写入 union 的一个成员并读取另一个成员是未定义的行为。

根据这个https://stackoverflow.com/a/11640603/1814023 C99/C11 允许类型双关

我对这两个帖子有点困惑,哪个是正确的?在理解类型双关与访问 union 成员方面需要帮助。

谢谢。

最佳答案

它是在 C89 中实现定义的:

C89 3.3.2.3 Structure and union members

With one exception, if a member of a union object is accessed after a value has been stored in a different member of the object, the behavior is implementation-defined. 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, and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them. Two structures share a common initial sequence if corresponding members have compatible types for a sequence of one or more initial members.

在 C99/C11 中,它是允许的,尽管当它是陷阱表示时,该值是不确定的。

C11 6.5.2.3 Structure and union members footnote

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.

关于c - 类型双关与联盟成员访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19511391/

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