A union is a special data type in C and C++ that allows you to store different data types in the same memory location. Unlike structures, where each member has its own memory location, a union uses a single memory location for all its members. This means that only one member of the union can be accessed at any time.
A union is defined similarly to a structure, but with the keyword union. Here’s a basic example:
#include <stdio.h>
union Data {
int intValue;
float floatValue;
char charValue;
};
In this example, union Data can hold an integer, a float, or a character, but only one of these types can be used at a time.
When initializing a union, you specify the initial value for one of its members. The other members will not have a meaningful value until they are assigned.
#include <stdio.h>
union Data {
int intValue;
float floatValue;
char charValue;
};
int main() {
// Initialize union
union Data data;
data.intValue = 10; // Only intValue is initialized
printf("Integer value: %d\n", data.intValue);
// Changing the value to float
data.floatValue = 3.14;
printf("Float value: %.2f\n", data.floatValue);
// Changing the value to char
data.charValue = 'A';
printf("Char value: %c\n", data.charValue);
// Printing all members to show the overlap
printf("Integer value after char assignment: %d\n", data.intValue);
printf("Float value after char assignment: %.2f\n", data.floatValue);
return 0;
}
Since a union shares the same memory for all its members, writing to one member affects the value of all other members due to memory overlap.
data.intValue = 10; initializes the intValue member, When data.intValue is printed, it shows 10.data.floatValue = 3.14; changes the value of floatValue, when data.floatValue is printed, it shows 3.14. The intValue may show a different value because the memory used for floatValue overlaps with intValue.data.charValue = 'A'; changes the value of charValue, whendata.charValue is printed, it shows 'A'. The intValue and floatValue will now show values affected by this assignment due to overlapping memory.Unions are useful for saving memory when you need to store different types of data but only one type at a time. They are particularly useful in low-level programming and embedded systems.