`union` — C++ Keyword
`union` — C++ Keyword
The union keyword in C++: defines a type where all members share the same memory.
`union` — C++ Keyword
The union keyword in C++: defines a type where all members share the same memory.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
unionDefines a type where all non-static data members share the same storage. The size of a union equals the size of its largest member.
union Name {
Type1 member1;
Type2 member2;
};
#include <cstdint>
#include <print>
union Bytes32 {
std::uint32_t value;
std::uint8_t bytes[4];
};
int main() {
Bytes32 u;
u.value = 0xDEADBEEF;
for (auto b : u.bytes) {
std::print("{:#04x} ", b);
}
std::println();
// Output (little-endian): 0xef 0xbe 0xad 0xde
}
char/unsigned char byte inspection).std::variant is the type-safe C++17 alternative for discriminated unions.unionint main() {
// Pick one facility from this reference page.
// Write the smallest program that exercises its main precondition,
// complexity rule, or lifetime constraint before scaling up.
return 0;
}