- union WeightType
- {
- long wtInOunces;
- int wtInPounds;
- float wtInTons;
- };
- WeightType weight;
At run time, the memory space allocated to the variable weight does not include room for three distinct components. Instead, weight can contain only one of the following: either a long value or an int value or a float value. The assumption is that the program will never need a weight in ounces, a wight in pounds, and a wight in tons simultaneously while executing. The purpose of a union is to conserve memory by forcing several values to use the same memory space, one at a time. The following code shows how the weight variable might be used.
- weight.wtInTons = 8.43;
- .
- .
- //Weight in tons is no longer needed. Reuse the memory spaces
- weight.wtInPounds = 35;
- .
- .
After the last assignment statement, the previous float value 8.43 is gone, replaced by the int values 35.