Unions

Unions are a sequence of bytes that are shared by more variables of different types. If the value of one of the variables within a union is set, all the other values are modified accordingly. For example, if a union charAndlong is defined:
union charAndlong
{
     char c;
     long l;
} aUnionVar;

aUnionVar.l = 0;
will set to 0 the l field, but also the c field, because the two share the least significant byte. On the other hand,
aUnionVar.c = 'd';
assigns to the c variable the value 'd', that is the integer value corresponding to 'd', which equals to 100. The value of the l field is also set to 100.

Example


#include <iostream>
using namespace std;

union charAndintAndlong
{
     char c;
     int i;
     long l;
};

int main()
{
     charAndintAndlong aVar;
     aVar.l = 0;  // initialized all fields to 0
     aVar.c = 'a';

     cout << "aVar.c: " << aVar.c << endl;
     cout <<  "aVar.i: " << aVar.i << endl; // prints 'a''s ASCII code.
     cout << "aVar.l: " << aVar.l << endl;
}

Output

aVar.c: a
aVar.i: 97
aVar.l: 97