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.
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:
Once you have defined a union, you can create variables of that type. For example, the following code creates two variables of type Data:
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:
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:
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
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.