Unions in C Language: Techniques for Memory Savings
In the C language, a union is a special data structure that allows storing different types of data in the same memory location. Unlike structures, which allocate independent memory for each member, a union only allocates enough space for its largest member. This makes unions an effective means of saving memory.
What is a Union?
A union is a user-defined data type that can contain multiple members of different types, but these members share the same memory area. In other words, at any given time, a union can only hold the value of one member.
Defining a Union
Here is a simple example demonstrating how to define and use a union:
#include <stdio.h>
// Define a union named Data
union Data {
int intValue;
float floatValue;
char charValue;
};
int main() {
// Create a variable of type Data
union Data data;
// Assign value to intValue
data.intValue = 10;
printf("data.intValue: %d\n", data.intValue);
// Assign value to floatValue
data.floatValue = 220.5f;
printf("data.floatValue: %.2f\n", data.floatValue);
// Note: intValue is no longer valid as it shares the same memory with float
printf("data.intValue after assigning float: %d\n", data.intValue);
return 0;
}
Output
Running the above code, you will see the following output:
data.intValue: 10
data.floatValue: 220.50
data.intValue after assigning float: -1071644672
From the output, it can be seen that when we assigned a <span>float</span> value to <span>floatValue</span>, the data previously stored in <span>int</span> became invalid. This is because all members share the same memory space.
How Unions Save Memory
Since all members share the same location, only the size required for the largest data type is allocated. For example, if you have the following two data types:
<span>int</span>: typically occupies 4 bytes.<span>double</span>: typically occupies 8 bytes.
If you use a structure to represent both, you would need 8 bytes (the size required for double), whereas using a union would only require 8 bytes, as that is the size needed for the largest element.
Example: Comparing Structure and Union
Below is a comparison of the memory usage between a structure and a union:
#include <stdio.h>
struct StructExample {
int intVal; // occupies 4 bytes
double doubleVal; // occupies 8 bytes
};
union UnionExample {
int intVal; // occupies 4 bytes
double doubleVal; // occupies 8 bytes
};
int main() {
struct StructExample s;
union UnionExample u;
printf("Size of struct: %zu bytes\n", sizeof(s));
printf("Size of union: %zu bytes\n", sizeof(u));
return 0;
}
Output
Running the above code, you will see output similar to the following:
Size of struct: 16 bytes
Size of union: 8 bytes
As shown, the structure occupies 16 bytes, while the union only occupies 8 bytes, demonstrating a significant difference between them.
Use Cases
- Embedded Systems: In resource-constrained environments, such as embedded systems, reducing program space is very important.
- Protocol Parsing: When dealing with network protocols or file formats, different fields may have different data types, and using unions provides a flexible way to handle these fields.
- Polymorphism: Although C does not have true object-oriented features, combining pointers and unions can simulate certain functionalities to achieve polymorphism.
Conclusion
Unions in the C language represent an efficient way to utilize memory. By allowing multiple data items to share the same location, we can significantly reduce the program’s resource requirements. However, it is important to be cautious when accessing non-active fields, as this can lead to undefined behavior. Properly leveraging this feature when appropriate will make your programs more efficient.