In other words, according to the C standard, is this code safe? (Assume uint8_t
is one byte)
void detectEndianness(void){
u
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.