Page 122 - Programming Microcontrollers in C
P. 122
More Structures 107
More Structures
There are two more important considerations that should be placed
under structures. The first of these is the union, and the second is bit
manipulations and bit fields.
Unions
A union is defined much the same as a struct.There is a signifi
cant difference, though. A union can have several different arguments,
each of which is a different type. The compiler, when it sees a union
declared, provides enough memory to hold the largest argument of
the union. When different arguments are used, the different types
occupy the same memory location. Consider the following sequence:
struct bothints
{
int hi,lo;
};
union both
{
long l;
struct bothints b;
}compound;
This sequence will cause the compiler to generate a structure that
contains two ints. The union both will provide space for which
ever is larger, a long or a struct bothints. Of course, a long
is the size of struct bothints , so enough memory will be
provided to store a long. In use, a sequence like
compound.b.hi = a;
compound.b.lo = b;
will place the int a into the upper location of compound , and b
will go into the lower location of compound. After these opera
tions, compound.l will contain a in its upper word, and b in its
lower word. If compound.l were used as a variable, it would be
this combination.
Unions are most often thought of as a method of saving memory.
If several variables are completely independent and never used at the