![]() |
![]() |
![]() |
![]() |
![]() |
|
To tell C to allow enough space for the largest of several different object types, you must define a union. A union is similar to a structure in that a union is a user-defined data type that you define in terms of a collection of typed structure variables. Unlike a structure, however, a union accommodates only one object at any one time. When you create an object belonging to a union, the space reserved is just that required to hold an object of the largest type that appears in the specification, rather than that required to hold a collection of objects.
Suppose, for example, that you define a trade to be the
union of a stock_trade and bond_trade. Then when you
create a trade object, C reserves enough space to hold either a
stock_trade or a bond_trade, but not both. The details of
space allocation are, as usual, somewhat implementation dependent, but the
following arrangement is likely:
*-- stock_trade object inside a trade_union object
|
| *-- Unoccupied space
v v
------------------------------- -------
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
| | | | | | | | | | | | | | | | | | | | |
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
| | | | | | | | | | | | | | | | | | | | |
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
---------------------------------------
^
|
*-- bond_trade object inside a trade_union object