Union in C Language
Sometimes, you need a data structure that can represent different data types depending on the situation. For instance, if you use a single structure to represent the quantity of fruit, it may need to be an integer (like 6 apples) at times and a float (like 1.5 kilograms of strawberries) at others.
In C, you can use a union to create a flexible data structure. A union can contain various members that share the same memory space, meaning only one member can hold a meaningful value at any given time. Assigning a new value to one member will overwrite the previous one, which is a key advantage for memory savings.
Here’s an example:
1 | union quantity { |
In this example, the union quantity
defines three members, but only one can hold a value at a time. The last assigned member will be the one that holds a meaningful value.
To use it, declare a variable of this type:
1 | union quantity q; |
You can also assign values using different syntax:
1 | union quantity q = {.count=4}; |
In the example above, if the last writing style does not specify a member name, it will be assigned to the first member.
After running this code, q.count
holds the value, while the other members do not. Accessing them can lead to undefined behavior until assigned a value.
1 | printf("count is %i\n", q.count); // count is 4 |
To access the weight
, you must assign it first:
1 | q.weight = 0.5; |
Once you assign a value to another member, the original member may no longer hold a meaningful value. The usage of unions is similar to structures otherwise.
Unions also support the pointer operator ->
:
1 | union quantity q; |
Here, ptr
points to q
, allowing access to its members directly.
When using unions with pointers:
1 | union foo { |
The type of the pointer is determined by the current member that is assigned a value.
You can also create type aliases for unions using typedef
:
1 | typedef union { |
This way, quantity
becomes an alias for the union type.
The primary benefit of using unions is memory efficiency, as they allow the reuse of memory for different data types, occupying space equal to the largest member.