C++ Union

💾 C++ union – Save Space by Sharing Memory

Imagine a tiny room where only one person can stay at a time. That’s exactly how a union works in C++! 🎒

A union lets you store different data types in the same memory space. But here’s the twist: only one member can hold a value at a time.

🛠️ Syntax

union UnionName {
    type1 var1;
    type2 var2;
    ...
};

🔧 Example: One Room, Many Guests

#include <iostream>
using namespace std;

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

int main() {
    Data d;

    d.i = 42;
    cout << "Integer: " << d.i << endl;

    d.f = 3.14;
    cout << "Float: " << d.f << endl;

    d.ch = 'A';
    cout << "Char: " << d.ch << endl;

    // But now, only 'ch' is valid, others are overwritten!
    return 0;
}
  

Try It Now

📦 How is union Different from struct?

  • struct gives each member its own memory space.
  • union makes all members share the same memory.
  • Use union when you want to save memory.

🧠 Easy Way to Remember

One place, many options: Use a union when different things take turns using the same memory.