Unions

Hi,
Wanted to check the values of the variables "hi" and "lo" after inserting values for the array char c[4] (this example is taken from the tutorial).
1
2
3
4
5
6
7
8
9
10
union mix_t 
{
  long l;
  struct 
 {
    short hi;
    short lo;
  } s;
  char c[4];
} mix;


----------------
The values I inserted in the array c were: 0,1,2,3
and the results were:
l = 50462976
hi = 256
lo = 770
----------------
Didn't understand why got these results, since:
char = 1 byte
short = 2 bytes
long = 4 bytes

Then, "l" should be 0123
"hi" should be 01
and "lo" 23

Is there any idea how it works?
Notice that the bit are changed when setting a value, this means that you should check the binary representation of those values on your computer, not the decimal representation
Do you know how binary representation can be checked by Visual Studio 2008?
There's an option to display in hex instead of decimal in the watch windows, but you can do it yourself:
50462976 -> 0x03020100
256 ->0x0100
770 -> 0x0302

You should avoid names like high and low unless you're certain that the source will only be compiled for architectures with the same endianness.
Now things become clear! Thanks :)
What 0x means?
0x in C++ means that the following number is in hexadecimal
It's worth mentioning that you should never use unions this way, because there's no guarantee that the fields will line up the way you expect. According to the standard you should only read from the field last written to -- anything else is undefined behavior.
So far I didn't find any use for this Unions thing, but still interesting!
If anyone wrote a code using it, I'll be glad to see.
The only time I ever needed to use a union was when using Yacc. I suppose they're somewhat useful if you're writing a dynamically typed class and you really want those extra bytes.
1
2
3
4
5
6
7
8
9
10
struct{
    enum{
        INTEGER,
        STRING
    } type;
    union{
        int integer;
        char *string;
    };
};
Usually I would just not use lines 6 and 9.
SDL does something similar to helios' example for events. It sticks a whole bunch of different structs inside a union, inside another struct and sends the whole thing as an event to your program. You determine which struct from the union to use based on the event type. This is really the only thing I can see a union being useful for.

Though in C++, you don't really need them, because you can just derive from a base class and let polymorphism take care of all that.
Topic archived. No new replies allowed.