Tuesday 3 January 2012

Unions

Unions and Structures are identical in all ways, except for one very important aspect. Only one element in the union may have a value set at any given time. Everything we have shown you for structures will work for unions, except for setting more than one of its members at a time. Unions are mainly used to conserve memory. While each member within a structure is assigned its own unique storage area, the members that compose a union share the common storage area within the memory. Unions are useful for application involving multiple members where values are not assigned to all the members at any one time.
Groups variables which share the same storage space.
A union is similar to a struct, except it allows you to define variables that share storage space. 
The syntax for defining unions is:
union [union-type-name]
  {
    type variable-names;
    ...
  } [union-variables] ;
For example,
union short_or_long
  {
    short i;
    long l;
  } a_number;
The compiler will allocate enough storage in a number to accommodate the largest element in the union. 
Elements of a union are accessed in the same manner as a struct. 
Unlike a struct, the variables 'a_number.i' and 'a_number.l' occupy the same location in memory. 
Thus, writing into one will overwrite the other.

No comments:

Post a Comment

host gator coupon