Unions are powerful things, but until you realise that the parts share the same memory, you'll struggle. David's picture and Carlo's talk both help, I hope.
They are very powerful in their limited way. Here's a sample of my code (no real secrets here):
union __ChannelsOn<br /> {<br /> BYTE Mask;<br /> struct {<br /> BYTE On1 : 1;<br /> BYTE On2 : 1;<br /> BYTE On3 : 1;<br /> BYTE On4 : 1;<br /> BYTE OnTOF : 1;<br /> BYTE Unused : 1;<br /> BYTE MasterOn : 1;<br /> BYTE ScanOn : 1;<br /> } Bits;<br /> } ChannelsOn;
I have some hardware that has a command I send to it to turn channels on and off. I send a byte made up of flag bits. I could say:
__ChannelsOn c;<br />c.Mask = 1 << 3 | 1 << 7;<br />SendChannels (c);
or I say:
__ChannelsOn c;<br />c.Mask = 0;<br />c.Bits.On3 = 1;<br />c.Bits.ScanOn = 1;<br />SendChannels (c);
Both do the same thing - but which is more readable?
They are also used to make the variant structure, used to talk with COM/VB.
It's equivalent to:
struct VARIANT<br />{<br /> int nType;<br /> union {<br /> int nInt;<br /> long lLong;<br /> DWORD dwDword;<br /> BSTR bstr;<br /> } Var;<br />};
I hope that helps a bit,
Iain.