typestar

Unions in C

One block of storage, several interpretations — but only one valid at a time.

#include <stdio.h>

typedef union {
    int as_int;
    float as_float;
    unsigned char bytes[4];
} Word;

void inspect(void) {
    Word w;
    w.as_int = 1;

    printf("size %zu\n", sizeof w);
    printf("bytes %u %u %u %u\n", w.bytes[0], w.bytes[1], w.bytes[2],
           w.bytes[3]);

    w.as_float = 1.0f;
    printf("float bits %08x\n", (unsigned) w.as_int);
}

How it works

  1. The size is that of the largest member.
  2. Writing one member and reading another is type punning.
  3. A tag field is what keeps a union honest.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
323
Tokens
106
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 64 seconds.

Type this snippet

Step 1 of 5 in Unions & layout, step 1 of 13 in Unions, bitfields & undefined behavior.

Next →