Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   Unions in C : A less used but a powerful feature of C (http://www.go4expert.com/articles/unions-c-powerful-feature-c-t15/)

Nicolas 13Jul2012 04:50

Re: Unions in C : A less used but a powerful feature of C
 
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 13Jul2012 13:57

Re: Unions in C : A less used but a powerful feature of C
 
This is really very good article! Well explained and it may be very useful to use unions :)

IkarusDowned 5Nov2012 10:15

Re: Unions in C : A less used but a powerful feature of C
 
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.


All times are GMT +5.5. The time now is 20:51.