I read about unions the other day( today ) and tried the sample functions that came with them. Easy enough, but the result was clear and utter garbage.
The first example is:
union Test
{
int Int;
struct
{
char byte1;
char byte2;
char byte3;
char byte4;
} Bytes;
};
where an int is assumed to have 32 bits. After I set a value Test t; t.Int = 7;
and then cout
cout << t.Bytes.byte1 << etc...
the individual bytes, there is nothing displayed, but my computer beeps. Which is fairly odd I guess.
The second example gave me even worse results.
union SwitchEndian
{
unsigned short word;
struct
{
unsigned char hi;
unsigned char lo;
} data;
} Switcher;
Looks a little wonky in my opinion. Anyway, from the description it says, this should automatically store the result in a high/little endian format when I set the value like
Switcher.word = 7656;
and calling with cout << Switcher.data.hi << endl
The result of this were symbols not even defined in the ASCII chart. Not sure why those are showing up.
Finally, I had an error when I tried correcting the example by, instead of placing Bytes at the end of the struct, positioning it right next to it. So instead of
struct {} Bytes;
I wanted to write
struct Bytes {};
This tossed me a big ol' error. What's the difference between these? Since C++ cannot have unnamed structs it seemed, at the time, pretty obvious that the Bytes positioned at the beginning and at the end are the things that name it. Except no, that's not the entire answer I guess. What is it then?