Topic 26 of 83
Unions
Overview
Unions are similar to structs, but all members share the *exact same memory location*. They are used for extreme memory optimization, storing only one of the values at any given time.
Syntax
cpp
union Data {
int intVal;
float floatVal;
char charVal;
};
Data d;
d.intVal = 42;
// If you now write to d.floatVal, it overwrites the intVal memory!Common Pitfalls
- Reading from a union member that wasn't the last one written to (Undefined Behavior).
Interview Tips
- The size of a union is equal to the size of its largest member.
- Unions are rarely used in modern high-level C++ but are common in low-level systems programming and embedded systems to save RAM.
Real-World Example
Demonstrating shared memory in a union.
example
cpp
#include <iostream>
using namespace std;
union ID {
int numericID;
char charID[4];
};
int main() {
ID myID;
myID.numericID = 65; // ASCII 'A'
cout << "Numeric: " << myID.numericID << endl;
cout << "Char: " << myID.charID[0] << endl; // Prints 'A'
return 0;
}