Saving memory with union
Sometimes a program will handle different
types of data using the same variable. In this situation, you have two choices:
you can create a struct containing all the possible different types you
might need to store, or you can use a union. A
union piles all the data into a single space; it figures out the amount
of space necessary for the largest item you’ve put in the union,
and makes that the size of the union. Use a union to save
memory.
Anytime you place a value in a
union, the value always starts in the same place at the beginning of the
union, but only uses as much space as is necessary. Thus, you create a
“super-variable” capable of holding any of the union
variables. All the addresses of the union variables are the same (in a
class or struct, the addresses are different).
Here’s a simple use of a
union. Try removing various elements and see what effect it has on the
size of the union. Notice that it makes no sense to declare more than one
instance of a single data type in a union (unless you’re just doing
it to use a different name).
//: C03:Union.cpp
// The size and simple use of a union
#include <iostream>
using namespace std;
union Packed { // Declaration similar to a class
char i;
short j;
int k;
long l;
float f;
double d;
// The union will be the size of a
// double, since that's the largest element
}; // Semicolon ends a union, like a struct
int main() {
cout << "sizeof(Packed) = "
<< sizeof(Packed) << endl;
Packed x;
x.i = 'c';
cout << x.i << endl;
x.d = 3.14159;
cout << x.d << endl;
} ///:~
The compiler performs the proper
assignment according to the union member you select.
Once you perform an assignment, the
compiler doesn’t care what you do with the union. In the example above,
you could assign a floating-point value to x:
x.f = 2.222;
and then send it to the output as if it
were an int:
cout << x.i;
This would produce
garbage.