`union` — C Keyword

`union` — C Keyword

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

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 (C)

Defines a type where all members share the same memory. The size equals the size of the largest member. Only one member is active at a time.

Syntax

union Name {
    Type1 member1;
    Type2 member2;
};

Example

#include <stdio.h>
#include <stdint.h>

union Bytes32 {
    uint32_t value;
    uint8_t  bytes[4];
};

int main(void) {
    union Bytes32 u;
    u.value = 0xDEADBEEF;

    printf("%08X\n", u.value);
    for (int i = 0; i < 4; ++i) {
        printf("%02X ", u.bytes[i]);   /* little-endian bytes */
    }
    printf("\n");
    return 0;
}

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