Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

union — shared member storage

The union keyword defines a type whose members share storage. Unlike struct, it does not retain their independent values simultaneously.

Version: C23; repository compiler flag, production runtime not attested

Syntax

union Value { int count; double real; };
union Value value = { .count = 7 };
value.real = 2.5;

union defines a union type. Members share storage; at most one member's value is stored at a time. Its size accommodates the largest member but may include extra padding bytes.

union Value names the type; Value alone is a tag, not a type alias. Access members using . or -> through a pointer. The initializer .count = 7 selects count.

Writing real replaces the stored value. Reading another member reinterprets the representation rather than numerically converting it; this may encounter a trap representation and cause undefined behavior.

A union does not track the selected member. Keep a separate tag, such as an enum, when needed.

Examples

#include <stdio.h>

union Value {
    int count;
    double real;
};

int main(void)
{
    union Value value = { .count = 7 };
    printf("count=%d\n", value.count);

    value.real = 2.5;
    printf("real=%.1f\n", value.real);
    return 0;
}

Result

count=7
real=2.5

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources