Unions in C
Unions in C
A union is a special data type that allows different data types to be stored in the same memory location. You
can define a union with multiple members, but only one member can contain a value at any given time. This
means that at any point, a union can store data for only one of its members.
int main() {
union Data data;
data.integer = 10;
printf("Data integer: %d\n", data.integer);
data.decimal = 220.5;
printf("Data decimal: %.2f\n", data.decimal);
return 0;
}
In this example, the data union can hold an integer, a float, or a string, but only one at a time. When you assign
a new value to a different member, it overwrites the previous data.
Key Differences
Memory Allocation: Structures allocate separate memory for each member, while unions share the same
memory location for all members, which is the size of the largest member.
Accessing Members: In structures, all members can be accessed at any time, and each member retains its
value. In unions, only one member can be accessed at a time, and changing the value of one member affects
the others due to the shared memory.
Size: The size of a structure is the sum of the sizes of all its members. The size of a union is the size of its
largest member.
Initialization: Structures allow for the initialization of multiple members at once. Unions only allow for the
initialization of the first member.
Practical Considerations
Use structures when you need to work with all the data members at once and maintain their individual values.
Use unions when you need to save memory and only one member is used at a time, such as in a type-
punning scenario where the same piece of memory is interpreted in different ways based on the context.