Node:Using unions, Previous:Declaration of unions, Up:union
Using unions
One way to tell what type of member is currently stored in the union
is to maintain a flag variable for each union. This can be done easily with
enumerated data. For example, for the int_or_float
type,
we might want an associated enumerated type like this:
enum which_member { INT, FLOAT };
Notice that we used all-uppercase letters for the enumerated values.
We would have received a syntax error if we had actually used the
C keywords int
and float
.
Associated union and enumerated variables can now be declared in pairs:
union int_or_float my_union1; enum which_member my_union_status1;
Handling union members is now straightforward. For example:
switch (my_union_status1) { case INT: my_union1.int_member += 5; break; case FLOAT: my_union1.float_member += 23.222333; break; }
These variables could even be grouped into a structure for ease of use:
struct multitype { union int_or_float number; enum which_member status; }; struct multitype my_multi;
You would then make assignments to the members of this structure in pairs:
my_multi.number.int_member = 5; my_multi.status = INT;