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'.
|
Newbie Member
|
|
| 13Jul2012,04:50 | #11 |
|
John Hoder
|
|
| 13Jul2012,13:57 | #12 |
|
This is really very good article! Well explained and it may be very useful to use unions
|
|
Newbie Member
|
|
| 5Nov2012,10:15 | #13 |
|
excellent post!
one thing: Quote:
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
};
You can, of course, use POINTERS to arbitarary types, since pointers are primatives.
shabbir
like this
|
