Newbie Member
13Jul2012,04:50   #11
Nicolas's Avatar
The first example is fairly bad.
When you use 'A' to initialize the char you leave the 3 other bytes uninitialized... Generating this random 577...

If you start by initializing x at 0 you set the 4 bytes of the union to 0.
Then the value of x after setting a to 'A' will give you 65. The result makes complete sense 65 being the ASCII value of the char 'A'.
John Hoder
13Jul2012,13:57   #12
Scripting's Avatar
This is really very good article! Well explained and it may be very useful to use unions
Newbie Member
5Nov2012,10:15   #13
IkarusDowned's Avatar
excellent post!
one thing:

Quote:
Types inside of unions are unrestricted, you can even use structs within unions.
it should be noted that for those using C++ and unions, this is not 100% true.
Unions are restricted to primative types, along with any type that has implicit constructors / destructors. For example:

Code:
struct A {
     int value;
};
 
struct B {
    int value;
   B() :value(100) {}
};
 
union AB {
    A a;
    B b;   //no good
};
At least in GCC, the above will throw a compilation exception.
You can, of course, use POINTERS to arbitarary types, since pointers are primatives.
shabbir likes this