Unions in C are special user-defined data types that allow storing different data types in the same memory location. They provide an efficient way to use the same memory space for multiple-purpose storage.
The syntax for declaring a union is similar to that of a C structure:
union union_name {
data_type member1;
data_type member2;
// ...
};
Here's a simple example demonstrating the use of a union:
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
data.i = 10;
printf("data.i: %d\n", data.i);
data.f = 220.5;
printf("data.f: %.2f\n", data.f);
strcpy(data.str, "C Programming");
printf("data.str: %s\n", data.str);
return 0;
}
In this example, the union Data
can store an integer, a float, or a string. However, it can only hold one value at a time.
While unions may seem similar to structures, they have a key difference:
Union | Structure |
---|---|
Members share the same memory space | Each member has its own memory space |
Size is equal to the largest member | Size is the sum of all members |
Can access only one member at a time | Can access all members simultaneously |
Unions are particularly useful in scenarios where you need to:
Understanding the memory layout of unions is crucial. Consider this example:
union Example {
int i; // 4 bytes
char c[4]; // 4 bytes
};
union Example ex;
ex.i = 0x12345678;
In this case, ex.c[0]
, ex.c[1]
, ex.c[2]
, and ex.c[3]
will contain the bytes of ex.i
in a specific order, depending on the system's endianness.
Unions in C provide a powerful tool for memory-efficient programming, especially in systems with limited resources. By understanding their behavior and use cases, you can leverage unions to create more flexible and efficient code.