How to use union in C.

A special type construction is the. They could be described as an either-or combination. Several variables are combined in a union, of which only one is needed. So only one of the specified elements can be used at a time. A union therefore takes up as much memory as the largest of its elements needs.

example

In a union, information is stored that is alternate to one another. The bank details could be given by a credit card with number and expiry month or a current account with account number and sort code: union tBank details {tKreditKartekarte; t current account account; };

Danger!

That only contains the pure data. It does not save which variant was last accessed. It does not prevent one version from being written and the other being read. It is therefore possible to use the map to write and off account to read. At best, the user will notice that the result is nonsensical.

Typecast

In some programs, the byte order is swapped between different machines with the help of the union. A 16-bit word consists of two bytes. Now the order of these bytes can be different on different machines. For example, on PCs, the least significant byte is taken first; on most RISC processors it is exactly the opposite. union tConverter {struct {unsigned char hi; unsigned char lo; } byte; unsigned short word; } Converter; int main () {converter.word = 7656; cout << (int) converter.byte.hi << endl; cout << (int) converter.byte.lo << endl; } As a result, the program delivers the values ​​232 and 29 on an Intel PC. Using one can easily lead to confusion. That is why you should only use them when there is no alternative.