C Unions

C Unions – Memory Sharing Structures

In C, a union is a special data type that allows multiple members to share the same memory location. It’s useful when you want to store different types of data in the same memory space but not at the same time.

🔹 What is a Union?

A union is similar to a structure, but unlike structures, all members of a union share the same memory location. Only one member can hold a value at any given time.

📦 Syntax of a Union

union UnionName {
    dataType member1;
    dataType member2;
    ...
};
  

Try It Now

📝 Example: C Union

Here’s a union with an int, a float, and a char — all sharing the same memory.

#include <stdio.h>

union Data {
    int i;
    float f;
    char ch;
};

int main() {
    union Data d;

    d.i = 100;
    printf("Integer: %d\n", d.i);

    d.f = 3.14;
    printf("Float: %f\n", d.f);

    d.ch = 'A';
    printf("Character: %c\n", d.ch);

    // Check how values overwrite each other
    printf("After assigning char, integer: %d\n", d.i);

    return 0;
}
  

Try It Now

📌 Key Points

  • All members share the same memory space.
  • Only the last assigned value is valid.
  • Used in memory-efficient scenarios like embedded systems, device drivers, etc.

🎯 Try This Yourself!

Modify the union and try storing values in different orders to see how data overwrites. It’s fun and a great memory-saving trick! 🧠