TExcelTAD
Home › C › C Unions

C Unions

A union looks just like a structure, but with one crucial difference: all of its members share the same memory. A struct holds all of its members at once; a union holds only one of them at a time. The union is as large as its largest member, and writing to one member overwrites the others.

Struct vs. union

c · try it yourself
#include <stdio.h>

struct S {
    int i;
    double d;
    char text[12];
};

union U {
    int i;
    double d;
    char text[12];
};

int main(void) {
    printf("sizeof(struct S) = %zu\n", sizeof(struct S));
    printf("sizeof(union U)  = %zu\n", sizeof(union U));
    return 0;
}
sizeof(struct S) = 32
sizeof(union U)  = 16

The struct needs room for an int, a double and 12 chars side by side (plus padding). The union only needs room for the largest member (12 chars), rounded up to 16 so that the double is properly aligned.

Using a union

Declare and access members with the dot operator, exactly like a struct. But only the member you wrote last holds a meaningful value:

c · try it yourself
#include <stdio.h>
#include <string.h>

union Value {
    int i;
    double d;
    char text[16];
};

int main(void) {
    union Value v;

    v.i = 42;
    printf("as int:    %d\n", v.i);

    v.d = 3.75;                     // overwrites the int
    printf("as double: %.2f\n", v.d);

    strcpy(v.text, "hello");        // overwrites the double
    printf("as text:   %s\n", v.text);
    return 0;
}
as int:    42
as double: 3.75
as text:   hello

Reading v.i after writing v.text would reinterpret the bytes of "hello" as an integer — that is almost never what you want.

Tagged unions: knowing which member is active

A union does not remember which member is currently valid. The standard solution is a tagged union: a struct that pairs the union with an enum (or int) "tag" telling you what is stored:

c · try it yourself
#include <stdio.h>

enum Kind { INT_VAL, REAL_VAL, TEXT_VAL };

struct Setting {
    const char *key;
    enum Kind kind;            // the tag
    union {
        int i;
        double r;
        const char *s;
    } as;                      // the payload
};

void print_setting(const struct Setting *st) {
    printf("%-10s = ", st->key);
    switch (st->kind) {
        case INT_VAL:  printf("%d (int)\n", st->as.i); break;
        case REAL_VAL: printf("%.2f (real)\n", st->as.r); break;
        case TEXT_VAL: printf("\"%s\" (text)\n", st->as.s); break;
    }
}

int main(void) {
    struct Setting settings[] = {
        {"volume", INT_VAL, {.i = 7}},
        {"gamma", REAL_VAL, {.r = 2.2}},
        {"language", TEXT_VAL, {.s = "en-GB"}},
    };
    for (int i = 0; i < 3; i++) {
        print_setting(&settings[i]);
    }
    printf("sizeof(struct Setting) = %zu\n", sizeof(struct Setting));
    return 0;
}
volume     = 7 (int)
gamma      = 2.20 (real)
language   = "en-GB" (text)
sizeof(struct Setting) = 24

Each setting stores either an int, a real or a text pointer, and the tag says which. This pattern appears in interpreters, JSON libraries, message formats and event systems.

The {.i = 7} syntax is a designated initialiser for the union member — it states which member gets the initial value.

Looking at the bytes of a value

Because members overlap, a union can expose the raw bytes of another type. Here a float is viewed through an array of bytes and a 32-bit integer (C explicitly allows reading a different member this way; the result depends on the machine's representation):

c · try it yourself
#include <stdio.h>
#include <stdint.h>

union FloatBits {
    float f;
    uint32_t bits;
    unsigned char bytes[4];
};

int main(void) {
    union FloatBits fb;
    fb.f = 1.0f;
    printf("1.0f as hex bits: 0x%08X\n", (unsigned) fb.bits);
    printf("bytes in memory:  %02X %02X %02X %02X\n",
           fb.bytes[0], fb.bytes[1], fb.bytes[2], fb.bytes[3]);
    return 0;
}
1.0f as hex bits: 0x3F800000
bytes in memory:  00 00 80 3F

The bytes appear "reversed" because x86 processors are little-endian: the least significant byte is stored first.

When to use unions

Use case Why a union helps
Values that can be one of several types (tagged unions) stores any variant in the space of the largest
Saving memory in large arrays of records only one variant's storage per element
Inspecting the byte representation of data different views of the same memory
Hardware registers in embedded code the same register accessed as a whole or by parts

Warning: A union by itself gives no safety: nothing stops you from reading the wrong member. Always pair it with a tag, and update the tag every time you change the active member.

Test yourself

How large is a union?

  1. The sum of its members' sizes
  2. At least the size of its largest member
  3. Always 8 bytes
  4. The size of its first member

You write u.i = 5; and then u.d = 2.5;. What happens to u.i?

  1. It is still 5
  2. It is overwritten because the members share memory
  3. It becomes 2
  4. Compile error

What is a tagged union?

  1. A union with a name
  2. A struct combining a union with a field that records which member is active
  3. A union of enums
  4. A union declared with typedef