vrijdag 15 juni 2007

Unions

A union is a data format that can hold different data types, but only one type at a time. That is, whereas a structure can hold , say, an int and a long and a double, a union can hold an int OR a long OR a double. The syntax is like that for a structure, but the meaning is different.

union one4all
{
int int_val;
long long_val;
double double_val;
};

You can use a one4all variable to hold an int, a long, or a double, just as long as you do so at different times:

one4all pail;
pail.int_val = 15; // store an int
cout << pail.int_val;
pail.double_val = 1.38; // store a double, int value is lost
cout << pail.double_val;

Thus, pail can serve as int variable on one occasion and as double variable at another. Because a union holds only one value at a time, it has to have space enough to hold its largest member. Hence, the size of the union is the size of its largest member.

One use for an union is to save space when a data item can use two or more formats but never simultaniously.
Example:

struct widget
{
char brand[20];
int type;
union id // format depends on widget type
{
long id_num; // type 1 widgets
char id_char[20]; // othher widgets
} id_val;
};
...
widget prize;
...
if (prize.type == 1)
cin >> prize.id_val.id_num;
else
cin >> prize.id_val.id_char;

And anonymous union has no nmae, in essence, its members become variables that share the same address. Naturally, only one member can be current at a time.

struct widget
{
char brand[20];
int type;
union // anonymous union
{
long id_num;
char id_char[20];
};
};
...
widget prize;
...
if (prize.type == 1)
cin >> prize.id_num;
else
cin >> prize.id_char;

Because tge union is anonymous, id_num and id_char are treated as two members of prize that share the same address. The need for an intermediate identifier id_val is eliminated. It is up to the programmer to keep track of which choice is active.

Geen opmerkingen: