A union in C++ is a data structure that allows storing different types of data in the same memory location.
Unlike structures (structs), where each member has its own storage area, in unions, all members share the same memory area.
This means that a union can have several members, but only one member can hold a value at any given time.
Unions are used when you need to store different types of data in the same variable, but only need to access one of them at a time.
In general, it is not a structure you should use frequently. It only makes sense in the case of some memory optimizations (generally, they are not common).
Basic Syntax
The basic syntax for defining a union is similar to that of a structure (struct), but using the keyword union instead of struct.
union UnionName {
data_type1 member1;
data_type2 member2;
// More members
};
For example,
union Data {
int integer;
float floating;
char character;
};
In this example, Data is a union that can contain an integer, a float, or a character (but only one of them at a time).
Accessing Union Members
To access the members of a union, the same syntax is used as for accessing structure (struct) members, using the dot operator (.).
Data data;
data.integer = 10;
std::cout << "Value of the integer: " << data.integer << std::endl;
In this example, the integer member of the union data is accessed and a value is assigned to it.
Size of a Union
The size of a union is equal to the size of its largest member. This is because the union reserves enough memory space to store the largest member, and all other members share the same memory location.
union Data {
int integer;
char string[10];
};
std::cout << "Size of the union Data: " << sizeof(Data) << std::endl; // Will print the size of an int
In this example, the size of the union Data will be equal to the size of an integer, since the integer member is the largest.
Using Unions to Save Memory
Unions can be used to save memory when you need to store different types of data in the same memory location, but only need to access one of them at a time.
union Value {
int integer;
float floating;
};
Value v;
v.integer = 10;
std::cout << "Value of the integer: " << v.integer << std::endl;
In this example, a Value union is used to store an integer or a float in the same memory location. This saves memory compared to using separate variables for each data type.
When using unions, it is important to consider some restrictions and considerations
- Concurrent Access: Only one member of the union can be accessed at a time. Changing the value of one member can affect the value of the other members.
- Shared Storage: All members share the same memory location, so modifying one member can affect the others.
- Incompatible Types: The data types stored in a union must be compatible with each other in terms of size and memory alignment.
