đ§ĩ Introduction to Unions in C
A union in C is a user-defined data type, similar to a structure, but it allows different variables to share the same memory location. This makes it memory-efficient when only one variable is used at a time.
đš What is a Union?
In a union, all members share the same memory. At any one time, only one member can hold a value. Assigning a new value to one member will overwrite the previous value.
✅ Syntax:
union UnionName {
dataType1 member1;
dataType2 member2;
...
};
Example:
union Data {
int i;
float f;
char str[20];
};
Size of the union will be equal to the largest member.
đš Example: Using 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 = %.1f\n", data.f);
printf("After assigning float, data.i = %d\n", data.i);
return 0;
}
đ§ Output:
data.i = 10
data.f = 220.5
After assigning float, data.i = 1123473408
Note: The integer value becomes garbage after assigning a float, because the same memory is reused.
đš Difference Between Structure and Union
Feature | Structure | Union |
---|---|---|
Memory | Each member has separate memory | All members share the same memory |
Size | Sum of all members | Size of the largest member |
Usage | Use all fields independently | Use only one field at a time |
đš When Should You Use Unions?
- To save memory.
- When you only need one value at a time.
- In embedded systems or memory-constrained programs.
đ Summary
Unions are powerful for optimizing memory use. They are especially helpful in embedded systems, data interpretation, and variant data storage.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ