`union` — C++ Keyword

`union` — C++ Keyword

The union keyword in C++: defines a type where all members share the same memory.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

union

Defines a type where all non-static data members share the same storage. The size of a union equals the size of its largest member.

Syntax

union Name {
    Type1 member1;
    Type2 member2;
};

Example

#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
}

Notes

Example in practice

int 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;
}