Accessing inactive union member and undefined behavior?

前端 未结 5 1290
独厮守ぢ
独厮守ぢ 2020-11-21 06:00

I was under the impression that accessing a union member other than the last one set is UB, but I can\'t seem to find a solid reference (other than answers clai

5条回答
  •  野的像风
    2020-11-21 06:38

    The C++11 standard says it this way

    9.5 Unions

    In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time.

    If only one value is stored, how can you read another? It just isn't there.


    The gcc documentation lists this under Implementation defined behavior

    • A member of a union object is accessed using a member of a different type (C90 6.3.2.3).

    The relevant bytes of the representation of the object are treated as an object of the type used for the access. See Type-punning. This may be a trap representation.

    indicating that this is not required by the C standard.


    2016-01-05: Through the comments I was linked to C99 Defect Report #283 which adds a similar text as a footnote to the C standard document:

    78a) If the member used to access 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.

    Not sure if it clarifies much though, considering that a footnote is not normative for the standard.

提交回复
热议问题