Programming in C

(Barry) #1
Working with Unions 375

The preceding whilestatement is easier to read when written like this:

while ( from != '\0' )
to++ = *from++;


*to = '\0';


Working with Unions


One of the more unusual constructs in the C programming language is the union.This
construct is used mainly in more advanced programming applications in which it is nec-
essary to store different types of data in the same storage area. For example, if you want
to define a single variable called x, which could be used to store a single character, a
floating-point number, or an integer, you could first define a union called, perhaps,
mixed:


union mixed
{
char c;
float f;
int i;
};


The declaration for a union is identical to that of a structure, except the keyword union
is used where the keyword structis otherwise specified.The real difference between
structures and unions has to do with the way memory is allocated. Declaring a variable
to be of type union mixed, as in


union mixed x;


does notdefine xto contain three distinct members called c,f,and i; rather, it defines x
to contain a singlemember that is called eitherc,f, or i. In this way, the variable xcan be
used to store either a charor a floator an int,but not all three (or not even two of
the three).You can store a character in the variable xwith the following statement:


x.c = 'K';


The character stored in xcan subsequently be retrieved in the same manner. So, to dis-
play its value at the terminal, for example, the following could be used:


printf ("Character = %c\n", x.c);


To store a floating-point value in x,the notation x.fis used:


x.f = 786.3869;


Finally, to store the result of dividing an integer countby 2 in x, the following statement
can be used:


x.i = count / 2;

Free download pdf