I had previously used unions with ease, but when I read this post and learned that this code
union ARGB
{
uint32_t colour;
struct componentsTag
{
uint8_t b;
uint8_t g;
uint8_t r;
uint8_t a;
} components;
} pixel;
pixel.colour = 0xff040201; // ARGB::colour is the active member from now on
// somewhere down the line, without any edit to pixel
if(pixel.components.a) // accessing the non-active member ARGB::components
is in fact undefinable behaviour
For example, reading from a union member other than the one who has lately been written to results in undefinable behaviour.
What is the intended use of unions if not this?
Could someone kindly provide a detailed explanation?