đŸ§ĩ Unions in C

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

unions in C programming, what is union in C, difference between union and structure in C, union syntax and example in C, when to use union in C, beginner union tutorial C, C language union data type, memory sharing in union

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

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