键入夯实VS联盟成员访问 [英] Type punning Vs Union member access
问题描述
根据本 http://stackoverflow.com/a/1812932/1814023 写作联盟成员之一,并阅读其他成员是不确定的行为。
和按本 http://stackoverflow.com/a/11640603/1814023 类型双关是允许在C99 / C11
我在这两个职位有点糊涂了,哪一个是正确的?
需要帮助理解型双关VS访问工会的成员。
I am bit confused on these two posts, which one is correct? Need help in understanding type punning Vs accessing the member of union.
感谢。
推荐答案
在C89它的实现定义的:
It's implementation-defined in C89:
有一个例外,如果一个工会值已经存储在对象的不同成员之后
对象访问的成员,该行为与实现。-defined 一个特殊的担保是为了简化使用工会提出:如果联盟
包含共享一个通用初始序列几种结构,如果联盟
对象当前包含这些结构之一,它允许检查任何它们的共同起始部分。两种结构有着共同的初始序列,如果相应成员具有兼容的类型的一个或多个初始成员的序列
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 aunion
contains several structures that share a common initial sequence, and if theunion
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,它是允许的,但是当它的陷阱重新presentation 的,价值是不确定的。
In C99/C11, it's allowed, although when it's trap representation, the value is indeterminate.
如果该构件用于读取联合的内容
对象是不一样的构件最后用来存储一个值在对象,的相应的部分对象重新值presentation是reinter $ p $如6.2.6所述PTED作为新类型的对象重新presentation(一个有时被称为'型双关'处理)。这可能是重新presentation一个陷阱。
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.
这篇关于键入夯实VS联盟成员访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!