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.. =)
Printable View
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.. =)
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:
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:Code:union RGBA
{ long value32;
struct tagColourBytes
{ unsigned char red;
unsigned char green;
unsigned char blue;
unsigned char alpha
} ColourBytes;
}
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.Code:RGBA myRGBAvar;
// older C-style declaration would be this:
// union RGBA myRGBAvar;
Yep, it's the other way round Harry :) R being least significant byte is last, they're stored ABGR