8.2 Unions

  -----------

 

      Unions can be used at any time to store values of different types in

  one object.

 

      The memory reserved for a union is determined by the size of the

  longest member of the union. All the members of the union are located in

  the same memory area at the same address.  The value of a current union

  member is lost when a value is assigned to another union member.

 

      In C-- there are so-called anonymous unions, which have no assigned

  name. Their members are addressed the same way as ordinary variables. For

  example:

 

  union

    dword regEAX;

    word  regAX;

    byte  regAL;

  };  // have declared that 3 variable are located on one and same

      // physical address

 

  declare three variables at the same physical address

  void test()

  {

      regEAX = 0x2C;

      BL = regAL; //importance 0x2C will turn out to be in register BL

  }

 

  value 0x2C assigned to register BL

 

      You can make unions of different variable types, arrays, string

  variables or structures. Unions may be global or local, and can even be

  found inside a structure (but at present structures cannot be used inside

  structures). Global unions can be initialized or uninitialized. An

  initialized union can be obtained by simply initializing the first member

  of the union. If the first member is not initialized but the next ones are,

  this will produce an error message.