Home / Learn Embedded C / Unions in C

Unions in C

A type where all fields share the same memory — used to reinterpret bytes in embedded code.

Quick summaryA type where all fields share the same memory — used to reinterpret bytes in embedded code.

How to think about this

Definition

A union looks like a struct but all its fields share the exact same memory, so writing one field overwrites the others — only one field is meaningfully "valid" at a time.

Why you need this

Embedded code often needs to look at the same bytes two ways: as a 32-bit sensor value, or as 4 separate bytes to send one at a time over UART — a union does this with zero copying.

How it works

A union's size equals its largest field; writing through one member and reading through another reinterprets the same underlying bytes (useful, but easy to misuse if you are not careful about types).

Where you'll see this

  • UART/SPI byte-splitting
  • Protocol encoding
  • Register reinterpretation

Try it

Splitting a 32-bit value into 4 bytes with shifts (the same result, without a union)C: edit and run

A union gives the compiler-level shortcut for this; shifting and masking gets the identical bytes out by hand.

Careful:Unlike a struct, a union only holds ONE field's worth of valid data at a time — writing one field and then reading a different one reinterprets the bytes, which is sometimes exactly the point and sometimes a bug.
Careful:This course's sandbox does not execute union code either, so the listing below is reference-only. The runnable "Try it" box gets the same 4 bytes out of a 32-bit value using shifts and masks instead (the "Bitwise Operations" group covers that technique in depth).
Reinterpreting a 32-bit value as 4 bytes with a union (reference only — not runnable in this sandbox)
#include <stdio.h>
union Reinterpret {
    unsigned int as_int;
    unsigned char as_bytes[4];
};
int main() {
    union Reinterpret u;
    u.as_int = 0x11223344;
    for (int i = 0; i < 4; i++) {
        printf("byte %d = 0x%02X\n", i, u.as_bytes[i]);
    }
    return 0;
}

Try it: merging bytes back into a 16-bit value

Merging two bytes back into a 16-bit valueC: edit and run

A union would let you write high_byte/low_byte as bytes and read as_int directly; shifting and OR-ing reconstructs the same value by hand -- the reverse of the byte-splitting example above.

Test what you just read

1. What is the key difference between a struct and a union?