|
|
|
|
|
|
|
The syntax for declaring a union type is identical to that of a struct type, except that the word union is substituted for struct. |
|
|
|
|
|
|
|
|
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 weight in pounds, and a weight 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 = 4.83;
.
.
.
// Weight in tons is no longer needed. Reuse the memory space.
weight.wtInPounds = 35;
.
.
. |
|
|
|
|
|
|
|
|
After the last assignment statement, the previous float value 4.83 is gone, replaced by the int value 35. |
|
|
|
|
|
|
|
|
It's quite reasonable to argue that a union is not a data structure at all. It does not represent a collection of values; it represents only a single value from among several potential values. On the other hand, unions are grouped together with the structured types because of their similarity to structs. |
|
|
|
|
|
|
|
|
There is much more to be said about unions, including subtle issues related to their declaration and usage. However, these issues are more appropriate in an advanced study of data structures and system programming. We have introduced unions only to present a complete picture of the structured types provided by C++ and to acquaint you with the general idea in case you encounter unions in other C++ programs. |
|
|
|
|
|
|
|
|
More on Choosing Data Structures |
|
|
|
|
|
|
|
|
Representing Logical Entities with Hierarchical Records |
|
|
|
|
|
|
|
|
We have demonstrated how to design algorithms and data structures in parallel. We progress from the logical or abstract data structure envisioned at the top level through the refinement process until we reach the concrete |
|
|
|
|
|