I've got three possible definitions, but I'm confused why there are so many. Does accessing the members behave any different than one over the other? What are the pros and cons? Just wondering if there are some rules to consider before using any of these.
For a
,r
,g
,b
,color
, I want to access the components in memory based on the datatype, or retrieve the unsigned int
of the color
at the same memory location.
struct RGBColor
{
union
{
BYTE a, r, g, b;
UINT color;
};
};
struct RGBColor2
{
union { BYTE a, r, g, b; };
union { UINT color; };
};
union RGBColor3
{
struct { BYTE a, r, g, b; };
struct { UINT color; };
};
I tried to look for a simple answer, but couldn't find any.
You misunderstood how unions work. The first struct contains a union with five alternatives: A byte named a, a byte named r, and so on.
The second struct contains two unions. The first contains one of four bytes, but only one at a time, and the second always contains a uint.
The third is a proper union. It either contains a struct of four bytes or a struct containing a Color. Now I don’t know what your plans are, but storing four bytes into the first alternative and reading them as a Color is undefined behaviour. What’s worse, it’s the kind of undefined behaviour that “works” on some compilers but not on others. Or worse, in a development version but not a released version.
(How would undefined behaviour not “work”? Say you wrote a zero into the Color. Then you write a, r,g and b and read the Color. Compiler says “you wrote 0 to Color, you didn’t write anything else to Color, therefore the Color must be 0”. Or the compiler says “you write a, r, g and b, then read Color. That’s undefined behaviour, so I remove the four byte stores”.)