8.7. UnionΒΆ
A union
construct is very similar to a struct
construct. Like a struct
, the union
declaration
specifies data types and variable names of a new data structure, of sorts.
Like with the struct
, the allocation of the memory comes not when
you define the union, but when you declare a variable of that type.
Accessing an item from a union uses the same syntax as accessing an item in
a struct. The difference is that a union
shares the same storage
area for all the elements rather than allocating a separate storage location
for each. Thus, a union actually only stores one element. It is the
programmers responsibility to keep track of what member name is being used
with a particular variable.
union size {
int pounds;
float tons;
};
union size bike, tank;
bike.pounds = 19;
tank.tons = 60.3;