🔹 Structure vs Union in C

đŸ§ĩ 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.

structure vs union in C, difference between struct and union, C programming structure and union comparison, memory allocation in union vs structure, union and structure example

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ