C++ Unions

Sage
Posts: 1,066
Joined: 2004.07
Post: #1
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?
Quote this message in a reply
Moderator
Posts: 1,140
Joined: 2005.07
Post: #2
Well, first of all it would probably be more correct to say "C unions." Rasp 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.
Quote this message in a reply
Moderator
Posts: 1,562
Joined: 2003.10
Post: #3
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:

Code:
union example_u {
  uint32_t i;
  unsigned char b[4];
};

union example_u myUnion = {1234};
It's a minor detail, but because of this, you may want to organize your union to have the largest type first.
Quote this message in a reply
Luminary
Posts: 5,143
Joined: 2002.04
Post: #4
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.
Quote this message in a reply
Sage
Posts: 1,066
Joined: 2004.07
Post: #5
Thanks for all the help. It makes sense now.
Quote this message in a reply
DoG
Moderator
Posts: 869
Joined: 2003.01
Post: #6
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.
Quote this message in a reply
Moderator
Posts: 1,562
Joined: 2003.10
Post: #7
Ah, cool. Didn't know that.
Quote this message in a reply
Post Reply