Programming in C

(Barry) #1

376 Chapter 17 Miscellaneous and Advanced Features


Because the float,char,and intmembers of xall exist in the same place in memory,
only one value can be stored in xat a time. Furthermore, it is your responsibility to
ensure that the value retrieved from a union is consistent with the way it was last stored
in the union.
A union member follows the same rules of arithmetic as the type of the member that
is used in the expression. So in
x.i / 2
the expression is evaluated according to the rules of integer arithmetic because x.iand
2 are both integers.
A union can be defined to contain as many members as desired.The C compiler
ensures that enough storage is allocated to accommodate the largest member of the
union. Structures can be defined that contain unions, as can arrays.When defining a
union, the name of the union is not required, and variables can be declared at the same
time that the union is defined. Pointers to unions can also be declared, and their syntax
and rules for performing operations are the same as for structures.
One of the members of a union variable can be initialized. If no member name is
specified, the firstmember of the union is set to the specified value, as in:
union mixed x = { '#' };
This sets the first member of x, which is c, to the character #.
By specifying the member name, any member of the union can be initialized like so:
union mixed x = { .f = 123.456; };
This sets the floating member fof the union mixed variable xto the value 123.456.
An automatic union variable can also be initialized to another union variable of the
same type:
void foo (union mixed x)
{
union mixed y = x;
...
}
Here, the function fooassigns to the automatic union variable ythe value of the argu-
ment x.
The use of a union enables you to define arrays that can be used to store elements of
different data types. For example, the statement
struct
{
char *name;
enum symbolType type;
union
{
int i;
Free download pdf