đ§ĩ Difference Between Structures and Unions in C
In C programming, both structures and unions are user-defined types that group different variables together. However, the way they handle memory is very different.
đš Structure Example
#include <stdio.h>
struct Person {
int age;
float height;
};
int main() {
struct Person p = {25, 5.9};
printf("Age: %d\n", p.age);
printf("Height: %.1f\n", p.height);
return 0;
}
✔️ Each member has its own memory space.
đš Union Example
#include <stdio.h>
union Data {
int age;
float height;
};
int main() {
union Data d;
d.age = 25;
printf("Age: %d\n", d.age);
d.height = 5.9;
printf("Height: %.1f\n", d.height);
printf("Age after assigning height: %d\n", d.age);
return 0;
}
⚠️ Assigning a new value overwrites the previous one due to shared memory.
đš Comparison Table
Feature | Structure | Union |
---|---|---|
Memory Allocation | Each member gets its own memory | All members share the same memory |
Size | Sum of all member sizes | Size of the largest member |
Access | Access all members at once | Access one member at a time |
Use Case | Store multiple values | Store a single value at a time |
Memory Efficiency | Less efficient | More efficient |
đš When to Use
- Structure: When you need all the data fields together (e.g., name, age, marks).
- Union: When only one value is needed at a time (e.g., sensor data format).
đ Summary
Use structures when you want to store and access multiple members independently. Use unions when memory is limited and only one member is needed at a time.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ