Unions
Unions behave like an "or" type.
Defining an union
In the example below, Variant
is either a char[10]
type, an int
type, OR a double
type. An union's value is stored in the same memory address, and you are responsible to "keep track" which data type it is currently using.
#include <cstdio>
union Variant {
char string[10];
int int_number;
double double_number;
};
int main() {
Variant v;
v.int_number = 42;
printf("Current v: %d\n", v.int_number);
//=> Current v: 42
v.double_number = 2.7182818284;
printf("Current v: %lf\n", v.double_number);
//=> Current v: 2.718282
// `v` is currently storing a double value
// from the last assignment, so trying to read
// it as `int` will give a gibberish result.
printf("Current v: %d\n", v.int_number);
//=> Current v: -1961734133
}
References
- C++ Crash Course (Josh Lospinoso) — 2. Types