Nicolas's Avatar, Join Date: Jul 2012
Newbie Member
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'.
Scripting's Avatar, Join Date: Jun 2010
John Hoder
This is really very good article! Well explained and it may be very useful to use unions
IkarusDowned's Avatar, Join Date: Nov 2012
Newbie Member
excellent post!
one thing:

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:

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 like this