Previous Topic Next topic Print topic


UNION

UNION is an attribute applied to a structure, which causes all immediate members of that structure to occupy the same memory locations. An immediate member is any member having a level number greater than its containing structure, equal to the level number of its fellow members, and less than the level of members it contains. Typically, an immediate member has a level number that is one greater than its containing structure.

All members of a UNION will start at the same address. If extra bytes are required for proper alignment of one member, those bytes will appear before the beginning of the structure, that is, before all other members. The size of the UNION will be the size of its largest member.

In the following example, the 30-character ADDRESS_STRING and the members of ADDRESS_PIECES occupy the same memory. Changing ADDRESS_PIECES.CITY changes ADDRESS_STRING:

DECLARE
   1 ADDRESS UNION,
      2 ADDRESS_STRING CHARACTER(30), 
      2 ADDRESS_PIECES,
            3 NUMBER CHARACTER(6), 
            3 STREET CHARACTER(12), 
            3 CITY CHARACTER(12);

In the following example, the data can be examined as 16 individual bits or as a single entity comprising one fixed binary number.

1 NUMBER UNION,
   2 FIXED_NUM FIXED BINARY(15), 
   2 FIXED_NUM_BIT BIT(16);
Note: Code based on a particular representation of data types is highly machine-dependent and should be used cautiously.
Previous Topic Next topic Print topic