PDA

Click to See Complete Forum and Search --> : Unions


Amon Ra
Aug 2nd, 2001, 09:48 PM
I am currently working on the cplusplus.com tutorials. I am at the point where they talk about typedef's and unions...
What are unions? I dont get it...could anyone explain to me?
Thanks in advance.. =)

HarryW
Aug 3rd, 2001, 03:08 AM
Unions are sets of variables that all occupy the same space in memory, so by changing one variable you change the others.

For instance, you could have a union representing a 32-bit colour value in RGBA format like this:

union RGBA
{ long value32;
struct tagColourBytes
{ unsigned char red;
unsigned char green;
unsigned char blue;
unsigned char alpha
} ColourBytes;
}I'm not certain that would map directly onto an RGBA value (the byte values might be in reverse order) but that's the idea. You could then declare a variable to use the union like this:
RGBA myRGBAvar;
// older C-style declaration would be this:
// union RGBA myRGBAvar;
You can then assign a 32-bit colour value to myRGBAvar.value32, and the values of myRGBAvar.ColourBytes.red, .green, .blue and .alpha would change because you have written to the same memory they occupy.

kedaman
Aug 4th, 2001, 05:08 AM
Yep, it's the other way round Harry :) R being least significant byte is last, they're stored ABGR