A union is a collection of member elements that overlay each other, occupying the same storage. The members can be structures, unions, elementary variables, and arrays. They need not have identical attributes.
The entire union is given a name that can be used to refer to the entire aggregate of data. Like a structure, each element of a union also has a name. An asterisk can be used as the name of a union or a member, when it will not be referred to. For example, reserved or filler items can be named asterisk.
Like a structure, a union can be at any level including level 1. All elements of a union at the next deeper level are members of the union and occupy the same storage. The storage occupied by the union is equal to the storage required by the largest member. Normally, only one member is used at any time and the programmer determines which member is used.
A union, like a structure, is declared through the use of level-numbers preceding the associated names.
Unions can be used to declare variant records that would typically contain a common part, a selector part, and variant parts. For example, records in a client file can be declared as follows:
Declare 1 Client,
2 Number pic '999999',
2 Type bit(1),
2 * bit(7),
2 Name union,
3 Individual,
5 Last_Name char(20),
5 First_Name union,
7 First char(15),
7 Initial char(1),
3 Company char(35),
2 * char(0);
In this example, Client is a major structure. The structure Individual, and the element Company are members of the union Name. One of these members is active depending on Type. The structure Individual contains the union First_name and the element Last_name. First_name union has First and Initial as its members, both of which are active. The example also shows the use of asterisk as a name. The description of a union is terminated by the semicolon that terminates a DECLARE statement or by a comma, followed by the declaration of another item.