In many programming languages, a union type allows for representing a single object/variable as multiple possible data types.
Language-specific
In C/C++
In C/C++, a union is able to store different data types in the same memory location. All members of a union will share the same memory location, though only one member can contain a valid value at any time. The size of a union is determined by its largest member. There’s also no type safety — it’s the programmer’s responsibility to track which type is active. And there’s no runtime mechanism to determine which type is active.
For example:
union Data {
int integer; // largest member is 32-bits
float decimal;
char string[20];
}We access members with the ./-> de-referencing notation.