Is type-punning through a union unspecified in C99, and has it become specified in C11?

后端 未结 4 1294
野的像风
野的像风 2020-11-22 04:17

A number of answers for the Stack Overflow question Getting the IEEE Single-precision bits for a float suggest using a union structure for type punning (e.g.: t

4条回答
  •  生来不讨喜
    2020-11-22 04:49

    However, this appears to violate the C99 standard (at least draft n1124), where section 6.2.6.1.7 states some stuff. Is this behavior actually unspecified under C99?

    No, you're fine.

    When a value is stored in a member of an object of union type, the bytes of the object representation that do not correspond to that member but do correspond to other members take unspecified values.

    This applies to data blocks of different sizes. I.e, if you have:

    union u
    {
        float f;
        double d;
    };
    

    and you assign something to f, it would change the lower 4 bytes of d, but the upper 4 bytes would be in an indeterminate state.

    Unions exist primarily for type punning.

提交回复
热议问题