Thuta Learning
C
AdvancedProgrammingBeginner

Unions

CLesson 2925 min

What you'll walk away with

  • Declare a union and explain why all its members start at the same address
  • Predict the sizeof a union, including the rounding up for alignment
  • Build a tagged union from an enum tag and a union payload, and check the tag before reading
  • Avoid reading a member other than the one last written in portable code

Explain it simply

Explain it simply

A union looks like a struct, but instead of giving every member its own space, it gives all members the same space. Picture a single parking spot that can hold a motorbike, a car or a van, one at a time. Parking the car there removes the motorbike, and the spot has to be as big as the largest vehicle it must fit.

So a union holds one value at a time, of one type chosen from a list. That saves memory when a piece of data can be one kind of thing or another but never both at once, such as a spreadsheet cell that contains either a number or some text.

Problem → Why → Solution

The problem: a union forgets which member you wrote

Imagine a settings file in which each value can be an integer or a decimal number. To save space you store values in a union, write 220.5 into the float member, and later another part of the program, which assumed the value was an integer, reads the int member. It gets a large, meaningless number, 1130135552 on a typical x86-64 PC, and nothing warns you.

setting.c
#include <stdio.h>

union Setting {
    int i;
    float f;
};

int main(void) {
    union Setting volume;
    volume.f = 220.5f;              /* stored as a float ...            */
    printf("%d\n", volume.i);       /* ... read back as an int: garbage */
    return 0;
}

Why does a garbage number come out?

A union does not remember which member was written last. Both members occupy the same four bytes, so reading i reinterprets the bit pattern of the float 220.5 as an integer. C allows this kind of reinterpretation, called type punning, as long as the bytes form a valid value of the new type, but the result depends on how the platform represents both types and is almost never the value you meant. The fix is a separate tag that records which member is active, checked before every read.

Core concept: shared storage and the active member

A union declaration lists its members just like a struct, union Data { int i; float f; char text[20]; };, but every member starts at offset 0. The union is therefore as large as its largest member, rounded up so the union can sit at an address suitable for its most strictly aligned member. With GCC on x86-64, union Data is 20 bytes while a struct with the same three members needs 28, and union { char c[5]; int i; } is 8, not 5, because its size is rounded up to a multiple of int's 4-byte alignment.

Writing a member makes it the active one. Its bytes overwrite the start of every other member, and any bytes that belong only to larger members take unspecified values. Reading a member other than the one last written is permitted in C and is called type punning: the stored bytes are reinterpreted as the new type, so the result depends on the platform (in C++ the same code is undefined behaviour). In ordinary programs, read only the member you last wrote; when you really need the bytes of a float, copying them into an integer with memcpy states that intent more clearly.

Because a union cannot tell you which member is active, real code pairs it with a tag inside a struct: struct Value { enum ValueKind kind; union { int i; double d; char text[16]; } as; };. The enum, covered in detail in the next lesson, names the possibilities; every write sets the tag and the payload together, and every read starts with a switch on the tag. This pattern is called a tagged union or discriminated union, and many languages build it in, Rust's enums for example. In C you maintain the rule yourself.

A union can be initialized with braces, but a plain {value} initializes only the first member. union Data d = {220.5}; converts 220.5 to int and stores 220 in d.i. To initialize a different member, name it with a designated initializer: union Data d = {.f = 220.5f};.

text
union Data { int i; float f; char text[20]; };   sizeof = 20
------------------------------------------------------------
              bytes 0..3  bytes 4..19
             +-----------+----------------------------+
 view as i:  |     i     |       (not part of i)      |
             +-----------+----------------------------+
 view as f:  |     f     |       (not part of f)      |
             +-----------+----------------------------+
 view text:  |               text[0..19]              |
             +----------------------------------------+
 three views of the same 20 bytes: all members start at offset 0,
 and only the member written last holds a meaningful value
Mental model: one parking spot, many vehicles
  1. All members share offset 0
  2. Size = largest member, rounded up
  3. Writing one member replaces the rest
  4. A tag records which member is live

If the code cannot answer "which member did I write last?", add a tag.

General pattern

c
union Name {
    type1 member1;
    type2 member2;
};

struct Tagged {
    enum Kind kind;                 /* which member is active */
    union Name as;
};
t.kind = KIND_ONE; t.as.member1 = value;           /* write tag + payload */
switch (t.kind) { case KIND_ONE: use(t.as.member1); break; /* ... */ }

A union is written like a struct, but its members share storage. In the tagged struct, the enum kind records the active member: every write sets both, and every read switches on kind first.

Example: one piece of memory, three kinds of value

The program puts three kinds of value into the same union one after another and reads each back right after writing it, which is the safe way to use an untagged union. It also compares the union's size with a struct holding the same members. The sizes are the same with GCC on 64-bit Windows and Linux.

union_data.c
#include <stdio.h>

union Data {
    int i;
    float f;
    char text[20];
};

struct AllAtOnce {
    int i;
    float f;
    char text[20];
};

int main(void) {
    union Data data;

    printf("sizeof(union Data) = %zu\n", sizeof(union Data));
    printf("sizeof(struct AllAtOnce) = %zu\n", sizeof(struct AllAtOnce));
    printf("members share one address: %s\n",
           (void *)&data.i == (void *)&data.f ? "yes" : "no");

    data.i = 10;
    printf("data.i = %d\n", data.i);

    data.f = 220.5f;              /* overwrites the bytes that held i */
    printf("data.f = %.1f\n", data.f);

    snprintf(data.text, sizeof data.text, "%s", "hello");
    printf("data.text = %s\n", data.text);
    return 0;
}

Code breakdown

  1. Lines 3-7union Data {

    The syntax matches a struct, but i, f and text all start at offset 0 and share one piece of storage.

  2. Lines 18-19sizeof(union Data)

    The union is 20 bytes, the size of its largest member text[20], while struct AllAtOnce needs 4 + 4 + 20 = 28 bytes.

  3. Lines 20-21(void *)&data.i == (void *)&data.f

    &data.i is an int * and &data.f a float *, so both are converted to void * before comparing. It prints yes without showing any address.

  4. Line 26data.f = 220.5f;

    Now f is the active member and the 10 stored in i is gone. Notice that the program never reads data.i after this line.

  5. Line 29snprintf(data.text, sizeof data.text, "%s", "hello");

    text becomes the active member. snprintf never writes past the 20-byte buffer and always terminates the string with '\0'.

You should see
sizeof(union Data) = 20
sizeof(struct AllAtOnce) = 28
members share one address: yes
data.i = 10
data.f = 220.5
data.text = hello

A tagged union in practice

Here is the tag-plus-payload pattern applied to a row of mixed values, the kind of thing a spreadsheet or a JSON parser needs. The designated initializers set the tag and the matching union member in one step, and print_value() never touches a member without checking kind first.

tagged_value.c
#include <stdio.h>

enum ValueKind { VALUE_INT, VALUE_DOUBLE, VALUE_TEXT };

struct Value {
    enum ValueKind kind;      /* the tag: which member is active */
    union {
        int i;
        double d;
        char text[16];
    } as;
};

void print_value(const struct Value *v) {
    switch (v->kind) {
    case VALUE_INT:
        printf("int: %d\n", v->as.i);
        break;
    case VALUE_DOUBLE:
        printf("double: %.2f\n", v->as.d);
        break;
    case VALUE_TEXT:
        printf("text: %s\n", v->as.text);
        break;
    default:
        printf("unknown kind %d\n", (int)v->kind);
        break;
    }
}

int main(void) {
    struct Value row[3] = {
        {.kind = VALUE_INT, .as.i = 42},
        {.kind = VALUE_DOUBLE, .as.d = 3.75},
        {.kind = VALUE_TEXT, .as.text = "Yangon"},
    };
    for (int n = 0; n < 3; n++) {
        print_value(&row[n]);
    }
    printf("sizeof(struct Value) = %zu\n", sizeof(struct Value));
    return 0;
}

It prints int: 42, double: 3.75 and text: Yangon. The default branch handles a tag that matches none of the expected values, which can happen when the data was read from a file or damaged by a bug. With GCC on x86-64, struct Value is 24 bytes: 4 for the tag, 4 bytes of padding so the double is 8-aligned, and 16 for the union.

Union or struct?

Questionunionstruct
How many members hold a value at once?One, the last one writtenAll of them
SizeLargest member, rounded up for alignmentSum of the members plus padding
Typical useOne of several kinds of value, with a tagA record with several properties

In real projects

Where this shows up in real projects

Tagged unions appear wherever a value can take one of several shapes. Interpreters and scripting engines store each runtime value as a tag plus a union of a number, a string pointer, an object pointer and so on. Parsers for JSON and configuration files produce nodes that are a number, a string, an array or an object, and compilers represent syntax tree nodes the same way.

Operating systems and libraries use unions in their APIs too. SDL's SDL_Event is a union of many event structs that all begin with a shared type field, so code reads event.type first and then the matching member. Network and file-format code sometimes overlays a union on a buffer to view the same bytes in different ways, which is exactly where this lesson's representation rules matter, and where careful code prefers explicit byte-by-byte parsing.

Common mistakes

Common mistakes

1. Reading a member you did not write last

After data.f = 220.5f;, printing data.i gives 1130135552 on a typical PC, not 220. The compiler does not warn, because the code is legal C. Keep a tag, and convert explicitly, as in (int)data.f, when you really want a number of another type.

2. Initializing the wrong member

union Data d = {220.5}; quietly initializes the first member, the int, with 220. Even -Wall -Wextra stays silent; only -Wconversion, through -Wfloat-conversion, reports that the conversion changes the value. Use a designated initializer: union Data d = {.f = 220.5f};.

3. Updating the payload without the tag

Setting v.as.d = 3.5; while v.kind still says VALUE_INT leaves the struct lying about its contents, and the next print_value() reads the wrong member. Write small setter functions that change the tag and the payload together, so the two cannot drift apart.

4. Assuming sizeof always equals the largest member

union { char c[5]; int i; } is 8 bytes on x86-64, not 5, because the size is rounded up to the int's alignment. Use sizeof rather than working out union sizes by hand.

Best practices

Best practices

  • Wrap every union that holds more than one kind of data in a struct with an enum tag.
  • Give each tagged union constructor or setter functions that set the tag and the payload together.
  • Add a default case to every switch on the tag to catch corrupted or unexpected values.

Mini challenge

Mini challenge: shapes with a tagged union

Represent circles and rectangles with one struct that holds a tag and a union, then compute their areas safely.

  • Write enum ShapeKind with SHAPE_CIRCLE and SHAPE_RECT, and a struct Shape holding kind plus a union with a circle (radius) and a rect (width, height)
  • make_circle(r) and make_rect(w, h) build a Shape with the tag and the payload set together
  • int area(const struct Shape *s, double *out) stores the area and returns 1, or returns 0 for an unknown tag
  • Print the areas of a circle of radius 1, a 2 x 3.5 rectangle and a shape whose tag was corrupted to 7
shapes.c
#include <stdio.h>

#define PI 3.14159265358979

enum ShapeKind { SHAPE_CIRCLE, SHAPE_RECT };

struct Shape {
    enum ShapeKind kind;
    // TODO: a union named "as" with circle.radius and rect.width / rect.height
};

struct Shape make_circle(double radius) {
    // TODO: set kind and as.circle.radius together
}

struct Shape make_rect(double width, double height) {
    // TODO: set kind and as.rect together
}

int area(const struct Shape *s, double *out) {
    // TODO: switch on s->kind; return 0 for an unknown kind
}

int main(void) {
    // TODO: make three shapes, corrupt the third one's kind to 7, then print
    //       "shape N: area X.XX" or "shape N: unknown kind, skipped"
    return 0;
}

Expected: The output should be: shape 0: area 3.14 shape 1: area 7.00 shape 2: unknown kind, skipped

Show hint

The union can contain two named structs: struct { double radius; } circle; and struct { double width, height; } rect;. A designated initializer such as {.kind = SHAPE_CIRCLE, .as.circle.radius = radius} sets the tag and payload at once. Corrupt the tag with shapes[2].kind = (enum ShapeKind)7;.

Show solution
shapes.c
#include <stdio.h>

#define PI 3.14159265358979

enum ShapeKind { SHAPE_CIRCLE, SHAPE_RECT };

struct Shape {
    enum ShapeKind kind;
    union {
        struct { double radius; } circle;
        struct { double width, height; } rect;
    } as;
};

struct Shape make_circle(double radius) {
    struct Shape s = {.kind = SHAPE_CIRCLE, .as.circle.radius = radius};
    return s;
}

struct Shape make_rect(double width, double height) {
    struct Shape s = {.kind = SHAPE_RECT, .as.rect = {width, height}};
    return s;
}

/* Returns 1 and stores the area, or 0 for an unknown tag. */
int area(const struct Shape *s, double *out) {
    switch (s->kind) {
    case SHAPE_CIRCLE:
        *out = PI * s->as.circle.radius * s->as.circle.radius;
        return 1;
    case SHAPE_RECT:
        *out = s->as.rect.width * s->as.rect.height;
        return 1;
    default:
        return 0;
    }
}

int main(void) {
    struct Shape shapes[3] = {make_circle(1.0), make_rect(2.0, 3.5), make_circle(2.0)};
    shapes[2].kind = (enum ShapeKind)7;   /* simulate corrupted input */

    for (int n = 0; n < 3; n++) {
        double a = 0.0;
        if (area(&shapes[n], &a)) {
            printf("shape %d: area %.2f\n", n, a);
        } else {
            printf("shape %d: unknown kind, skipped\n", n);
        }
    }
    return 0;
}

Quick quiz 1 / 3

With GCC on x86-64, what is sizeof(union U) for union U { char c[5]; int i; };?

Quick quiz 2 / 3

Given union Data { int i; float f; }; union Data d = {220.5};, what does printf("%d", d.i) print?

Quick quiz 3 / 3

Which design lets code know which union member is safe to read?

What to remember

  • All members of a union start at the same address, so only one holds a meaningful value at a time.
  • The sizeof a union is its largest member, rounded up to a multiple of its strictest alignment.
  • Pair a union with an enum tag in a struct, set both together, and switch on the tag before reading.
  • Reading a member other than the last one written reinterprets bytes and depends on the platform; avoid it in ordinary code.
  • A plain brace initializer sets the first member; use .member = value for any other one.

SEI CERT C Coding Standard — Carnegie Mellon SEI

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Unions | Thuta Learning