Unions and Their Risks
Share memory between types.
What Is a Union?
A union lets several members share the same memory. Only one member is valid at a time, and the union is only as big as its largest member.
#include <iostream>
union Number {
int i;
float f;
};
int main() {
Number n;
n.i = 42;
std::cout << n.i << "\n";
}Size of a Union
Because members overlap, sizeof a union equals the size of its largest member (plus any alignment padding), not the sum.
#include <iostream>
union Mix { char c; int i; double d; };
int main() {
std::cout << sizeof(Mix) << "\n"; // size of double (often 8)
}All lessons in this course
- Scoped enum class
- Unions and Their Risks
- std::variant
- std::visit