Unions in C Language
In C language, a union is a user-defined data type that allows you to store different data types in the same memory location. Like structures, unions allow you to group variables of different types under a single name, but with a key difference: only one member of a union can be used at a time.
A union declaration defines a blueprint for the union, specifying the name of the union and the member variables that it contains. Each member variable can be of a different data type, and they all share the same memory space. The size of a union is determined by the size of its largest member.
Here’s an example of a union declaration in C:
union my_union {
int i;
float f;
char c;
};
This defines a union called “my_union” that contains three member variables: an integer named “i”, a floating-point number named “f”, and a character named “c”. All three member variables share the same memory location.
Once a union is defined, you can declare variables of that type, just like any other data type in C:
union my_union u; // Declare a variable of type "my_union" named "u"
You can then access the member variables of the union, but only one member variable can be used at a time:
u.i = 42; // Assign a value to the "i" member variable
printf("%d\n", u.i); // Access the "i" member variable
u.f = 3.14; // Assign a value to the "f" member variable
printf("%f\n", u.f); // Access the "f" member variable
u.c = 'A'; // Assign a value to the "c" member variable
printf("%c\n", u.c); // Access the "c" member variable
Note that when you assign a value to a member variable, it overwrites the value of any other member variable that was previously assigned. This is because all member variables share the same memory space. The value of a member variable can only be safely accessed if you know which member variable is currently in use.