|
|
coherent
union C Keyword union
Multiply declare a variable
A union defines an area of storage that can accept any one of
several types of data. In effect, it is a multiple declaration
of a variable. For example, a union may be declared to consist
of an int, a double, and a char *. Any one of these three
elements can be held by the union at a time, and will be handled
appropriately by it. For example, the declaration
union {
int number;
double bignumber;
char *stringptr;
} example;
allows example to hold either an iinntt, a ddoouubbllee, or a pointer to a
cchhaarr, whichever is needed at the time. All of these have the
same address. The elements of a uunniioonn are accessed like those of
a ssttrruucctt: for example, to access nnuummbbeerr from the above example,
type eexxaammppllee.nnuummbbeerr.
unions are helpful in dealing with heterogeneous data, especially
within structures; however, you are responsible for keeping track
of what data type the union is holding at any given time. Pas-
sing a double to a union and then reading the union as though it
held an int will yield results that are unpredictable, and
probably unwelcome.
***** Example *****
For an example of how to use a union in a program, see the entry
for byte ordering.
***** See Also *****
C keywords, struct, structure
COHERENT Lexicon Page 1
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.