C++ Unions
Can anyone explain a union? I'm writing my own GUI using SDL, but I can't figure out how unions work in terms of the SDL_Event. I kind of understand how all the data inside shares the same memory, but even that is a complex idea to me. Any help?
Well, first of all it would probably be more correct to say "C unions."
C++ just includes them to remain compatible with C.
The way unions work is they take up the size of the largest element. Other elements then use the same block of memory, but just treat it as if it's that type. For example, if you had a union of a float and an unsigned int, you could get the hexadecimal code of the float without casting. You could also do byte swapping by having a union of a type and an unsigned char array of the same type, and swapping the bytes in the array. For types of different sizes, I think they all start on the first byte, but I'm not 100% sure.
C++ just includes them to remain compatible with C.The way unions work is they take up the size of the largest element. Other elements then use the same block of memory, but just treat it as if it's that type. For example, if you had a union of a float and an unsigned int, you could get the hexadecimal code of the float without casting. You could also do byte swapping by having a union of a type and an unsigned char array of the same type, and swapping the bytes in the array. For types of different sizes, I think they all start on the first byte, but I'm not 100% sure.
An interesting and slightly obscure thing I learned about unions a little while ago: If you want to assign an initial value to a union variable, you can only do it to the first item in the union. The syntax is similar to initial assignment of arrays or structs. Example:
It's a minor detail, but because of this, you may want to organize your union to have the largest type first.
Code:
union example_u {
uint32_t i;
unsigned char b[4];
};
union example_u myUnion = {1234};
You should always organize the union to have the field with the strictest alignment requirements first, since I believe the alignment of the union is the alignment of the first member. That means vector types before long doubles before doubles before long longs, longs and void*s, before ints and floats, before shorts, before chars -- including arrays thereof.
Thanks for all the help. It makes sense now.
ThemsAllTook Wrote:An interesting and slightly obscure thing I learned about unions a little while ago: If you want to assign an initial value to a union variable, you can only do it to the first item in the union. The syntax is similar to initial assignment of arrays or structs.
...
It's a minor detail, but because of this, you may want to organize your union to have the largest type first.
That is not the case:
Code:
union example_u {
uint32_t i;
unsigned char b[4];
};
union example_u myUnion = {.b={'a','b','c','d'}};You can use named members for union initialization.
Ah, cool. Didn't know that.

