In C, a union is a special data structure that allows storing different data types in the same memory location. Unlike a structure, where each member has its own memory space, all members of a union share the same memory. This allows a union to store one value at a time, reducing memory usage.
Syntax:
union UnionName {
dataType member1;
dataType member2;
…
};
Example:
#include <stdio.h>
union Data {
int i;
float f;
char c;
};
int main() {
union Data data;
data.i = 10;
printf(“%d\n”, data.i); // Prints 10
data.f = 3.14;
printf(“%f\n”, data.f); // Prints 3.14
return 0;
}
In the above example, data can hold an int, float, or char, but only one at a time. Unions are useful for memory-efficient applications, especially in embedded systems.