I have a few questions regarding unions and what is safe. Please check my understanding. Given a union like union { uint16_t ab; struct { uint8_t b; uint8_t a; }; };
:
-
In C99 and onwards, it is ok to for example set
ab
and then readb
ora
. And then if I modifiedb
, readingab
later on would also be fine. -
But in CPP, the above is UB.
-
Whether
a
orb
is the most significant bit (msb) depends on the endianness of the machine. For example, here a is the msb for me as it is the second struct field and my machine is little-endian. Therefore, we can’t really use unions without caring about endianness.
Is my understanding correct?