Loading...
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
A union is a special data type where all members share the SAME memory location. It can hold only one of its members at a time.
union Data {
int i;
float f;
char str[20];
};
Data d;
d.i = 10; // Memory now holds an intSetting a new member overwrites the previous one. Accessing a member that wasn't set last results in undefined data.
The size of a union is the size of its LARGEST member. Ideal for memory-constrained systems.
Modern C++ usually prefers std::variant over unions as it's type-safe and "knows" which member is currently active.