Skip to main content

Lesson 4 of 5

union - Overlapping Memory & Bit-fields

A `union` is like a `struct` except all members share the same memory starting at offset 0. `sizeof(union)` = size of the largest member. Only one member is 'active' at a time - writing one and reading another is only valid in specific cases (type punning). Bit-fields allow packing multiple small integer values into a single word.

11 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

union - Type Punning, Tagged Union & Bit-fields

union - Type Punning, Tagged Union & Bit-fields
#include <stdio.h>
#include <stdint.h>

/* ── Basic union - shared memory ────────────────────────── */
union NumericValue {
    int     i;
    float   f;
    double  d;
};

/* union size = largest member */

/* ── Tagged union - the safe pattern ─────────────────────
   A struct containing a union + a tag indicating which member
   is currently active. This is how you use unions safely.  */
typedef enum { TYPE_INT, TYPE_FLOAT, TYPE_STR } ValueType;

typedef struct {
    ValueType type;
    union {
        int         i;
        float       f;
        const char *s;
    } as;
} Value;

void print_value(const Value *v) {
    switch (v->type) {
        case TYPE_INT:   printf("int:   %d
",   v->as.i); break;
        case TYPE_FLOAT: printf("float: %.2f
", v->as.f); break;
        case TYPE_STR:   printf("str:   %s
",   v->as.s); break;
    }
}

/* ── Type punning - reading raw bytes via union ─────────── */
union Float32 {
    float    f;
    uint32_t bits;   /* same 4 bytes, interpreted as uint32_t */
};

/* ── Bit-fields - packing multiple flags into one word ───── */
typedef struct {
    unsigned int day   : 5;   /* 0-31: 5 bits */
    unsigned int month : 4;   /* 0-15: 4 bits */
    unsigned int year  : 23;  /* up to ~8M: 23 bits */
} PackedDate;                 /* sizeof = 4 bytes (one int)   */

typedef struct {
    unsigned int read    : 1;
    unsigned int write   : 1;
    unsigned int execute : 1;
    unsigned int        : 5;  /* padding - unnamed bit-field   */
} Perms;                      /* sizeof = 1 byte               */

int main(void) {
    /* ── Tagged union ────────────────────────────────────── */
    Value vals[] = {
        { TYPE_INT, { .i = 42 }       },
        { TYPE_FLOAT, { .f = 3.14f }  },
        { TYPE_STR, { .s = "hello" }  },
    };
    for (int i = 0; i < 3; i++) print_value(&vals[i]);

    /* ── Type punning bits of a float ─────────────────────
       Standards-conforming way to inspect float binary repr */
    union Float32 x;
    x.f = -1.0f;
    printf("-1.0f bits = 0x%08X
", x.bits);  /* BF800000 */

    /* ── Bit-fields ──────────────────────────────────────── */
    PackedDate d = { .day=20, .month=3, .year=2026 };
    printf("Date: %u/%u/%u  (sizeof=%zu)
",
           d.day, d.month, d.year, sizeof(d));

    Perms p = { .read=1, .write=1, .execute=0 };
    printf("rwx: %u%u%u
", p.read, p.write, p.execute);

    return 0;
}

Common Mistakes

  • Reading the wrong union member - writing `u.f = 3.14` then reading `u.i` is type punning and produces implementation-defined results in C (only strictly valid via memcpy or the specific union-based punning rule in C99). Know which member is active.
  • Relying on bit-field layout across platforms - bit-field bit ordering and padding are implementation-defined. Never use bit-fields for on-disk or on-network formats.
  • Union size surprise - `sizeof(union { char c; double d; })` = 8, not 9. The union is sized for the largest member. Adding more members never makes the union larger than the largest.

Tip

Tip

Practice union Overlapping Memory Bitfields in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Unions store different types in the same memory location, taking only the size of the largest member

Practice Task

Note

Practice Task - (1) Write a working example of union Overlapping Memory Bitfields from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with union Overlapping Memory Bitfields is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.

Key Takeaways

  • A `union` is like a `struct` except all members share the same memory starting at offset 0.
  • Reading the wrong union member - writing `u.f = 3.14` then reading `u.i` is type punning and produces implementation-defined results in C (only strictly valid via memcpy or the specific union-based punning rule in C99). Know which member is active.
  • Relying on bit-field layout across platforms - bit-field bit ordering and padding are implementation-defined. Never use bit-fields for on-disk or on-network formats.
  • Union size surprise - `sizeof(union { char c; double d; })` = 8, not 9. The union is sized for the largest member. Adding more members never makes the union larger than the largest.

Topics in This Module

0/5 done