Chapter 05 Compound Data Type - Constructed Type
4. Union Type
Union Type is a kind of compound data type that can represent several types of data. As we known, each data has its unique type and the memory will allocate to it a corresponding kind of room with appropriate size and whatever needed. While the union type is composed of several base types, the memory will give it a room with the size of the maximum of these base types so that each of them can live in it but only one of them will actually live in it.
So we can consider the union type as a multi-functional type but can just run one of its all functions.
Basic manipulation for the union type is just like former types that have been introduced, so I’ll just give an example to help you confirm your assumption.
struct Line{
double x1, y1, x2, y2;
};
struct Rectangle{
double left, top, right, bottom;
};
struct Circle {
double x, y, r;
};
union Figure {
Line line;
Rectangle rect;
Circle circle;
}
const int MAX_NUM_OF_FIGURES = 100;
Figure figures[MAX_NUM_OF_FIGURES];
//representing a group of figures including line, rectangle and circle.