While C structs allow you to group distinct data types together where each member has its own dedicated memory space, Unions provide a completely different approach. In a union, all members share the exact same memory location.
Unions are advanced constructs used primarily in systems programming, embedded systems, and network packet parsing, where memory conservation is absolutely critical. This detailed guide will walk you through declaring, using, and mastering unions in C to optimize your applications.
A union is a user-defined data type similar to a structure. The key difference is memory allocation.
struct): Allocates separate memory for each member. The total size is the sum of the sizes of all members (plus padding).union): Allocates a single block of memory large enough to hold the largest member. All members share this memory.Because memory is shared, only one member can contain a valid value at any given time.
You define a union using the union keyword, followed by the union tag and its members enclosed in curly braces.
union Data {
int i;
float f;
char str[20];
};
In the above example, the size of union Data will be 20 bytes. Why? Because the largest member is str[20], which takes 20 bytes. i (4 bytes) and f (4 bytes) will safely fit within this 20-byte block.
Just like structures, you use the dot operator (.) to access members of a union. However, you must be extremely careful to only read from the member that was most recently written to.
#include <stdio.h> #include <string.h>union Data { int i; float f; char str[20]; };
int main() { union Data data; // Using one member at a time data.i = 10; printf("data.i : %d\n", data.i); data.f = 220.5; printf("data.f : %.1f\n", data.f); strcpy(data.str, "C Programming"); printf("data.str : %s\n", data.str); return 0; }
Notice how we assign and immediately print each member? This ensures data integrity.
If you attempt to assign values to all members at once and then read them, you will encounter data corruption. Because they share memory, writing to a new member overwrites the data of the previous member.
#include <stdio.h> #include <string.h>union Data { int i; float f; char str[20]; };
int main() { union Data data; // Assigning all at once data.i = 10; data.f = 220.5; strcpy(data.str, "C Programming"); // The integer and float values are now corrupted! printf("data.i : %d\n", data.i); // Garbage value printf("data.f : %f\n", data.f); // Garbage value printf("data.str : %s\n", data.str); // Valid value return 0; }
Why use unions if they are so restricted?
float bit-by-bit as an int).How is the total memory size of a union determined?