0
0
C++programming~5 mins

Union basics in C++

Choose your learning style9 modes available
Introduction

A union lets you store different types of data in the same memory space, but only one at a time. It helps save memory when you need to work with different data types but never all together.

When you want to save memory by sharing space for different data types.
When you have a variable that can hold different types of values at different times.
When you want to interpret the same data in multiple ways.
When working with low-level data like hardware registers or network packets.
Syntax
C++
union UnionName {
    type1 member1;
    type2 member2;
    // more members
};
Only one member can hold a value at a time; all members share the same memory.
The size of the union is the size of its largest member.
Examples
This union can hold either an int or a float, but not both at the same time.
C++
union Data {
    int i;
    float f;
};
The union can store a char or a double. The memory size equals the size of double.
C++
union Value {
    char c;
    double d;
};
Sample Program

This program shows how the union stores an int first, then a float. When the float is set, the int value changes because both share the same memory.

C++
#include <iostream>
using namespace std;

union Data {
    int i;
    float f;
};

int main() {
    Data data;
    data.i = 10;
    cout << "data.i = " << data.i << endl;
    data.f = 3.14f;
    cout << "data.f = " << data.f << endl;
    cout << "data.i after setting f = " << data.i << endl;
    return 0;
}
OutputSuccess
Important Notes

Writing to one member and reading from another can cause unexpected values because they share memory.

Use unions carefully to avoid confusing bugs.

Summary

Unions share memory for all members, saving space.

Only one member can hold a valid value at a time.

Useful for memory-efficient storage of different data types.