Is it safe to detect endianess with union?

后端 未结 3 819
陌清茗
陌清茗 2021-01-11 18:28

In other words, according to the C standard, is this code safe? (Assume uint8_t is one byte)

void detectEndianness(void){
    u         


        
3条回答
  •  走了就别回头了
    2021-01-11 18:44

    The standard (available in the linked online draft) says in a footnote that it is allowed to access a different member of the same union than the member previously written:

    95) 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.

    But the footnote also mentions a possible trap representation, and the only data type that is guaranteed by the standard to be safe concerning trap representations is unsigned char. Accessing trap representations may be undefined behaviour; and although I don't think that unit_32 may yield a trap representation on your platform, it is actually implementation dependant whether accessing this member is UB or not.

提交回复
热议问题