C Unions

A union in C is a user-defined data type that allows you to store different data types in the same memory location. This can be useful for saving memory, especially when you only need to store one value at a time.

C Union

To define a union, you use the union keyword followed by the name of the union and a list of its members. Each member can be a variable of a different data type. For example, the following code defines a union called Data that has three members: i, f, and str:

union Data { int i; float f; char str[20]; };

Once you have defined a union, you can create variables of that type. For example, the following code creates two variables of type Data:

union Data data1, data2;

To access the members of a union, you use the dot operator (.). For example, the following code assigns the value 10 to the i member of the data1 variable:

data1.i = 10;

To access a different member of a union, you must first set the value of that member. For example, the following code assigns the value 3.14 to the f member of the data1 variable:

data1.f = 3.14;

When you assign a value to a member of a union, the values of all other members are overwritten. This is because all members of a union share the same memory location.

The following code shows a complete example of how to use unions in C:

Full Source | C union
#include <stdio.h> union Data { int i; float f; char str[20]; }; int main() { union Data data1, data2; data1.i = 10; printf("data1.i = %d\n", data1.i); data1.f = 3.14; printf("data1.f = %f\n", data1.f); data2.str = "Hello, world!"; printf("data2.str = %s\n", data2.str); return 0; }
//Output: data1.i = 10 data1.f = 3.140000 data2.str = Hello, world!

Conclusion

A union is a data structure that enables the grouping of variables of different data types under a single name, sharing the same memory location. Unlike structures, unions can hold only one value at a time and are useful for scenarios where you need to interpret the same memory space in different ways, allowing for efficient representation of diverse data formats or values within the same memory footprint.