Back to Blog

C in 100 Seconds: Unions — Shared Memory | Episode 25

Daryl WongDaryl Wong

Video: C in 100 Seconds: Unions — Shared Memory One Field at a Time | Episode 25 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Unions in C — Shared Memory, One Field at a Time

C in 100 Seconds, Episode 25


A union looks like a struct, but there is a critical difference — all members share the same chunk of memory. Only one field is valid at any given time.

Union vs Struct

A struct allocates space for every member. A union allocates space for the largest member, and all fields overlap:

union Value {
  int i;
  float f;
  char c;
};

This union is 4 bytes — the size of its largest member (int or float). A struct with the same fields would be 12 bytes.

Only One at a Time

Set the int, and that value occupies the shared memory:

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

Now set the float — it overwrites the same bytes:

v.f = 3.14;
printf("float: %.2f\n", v.f);  // 3.14
printf("int: %d\n", v.i);       // garbage!

Reading the int after writing the float gives garbage because the bit pattern for 3.14 as a float is meaningless when interpreted as an int.

sizeof Proves It

printf("sizeof union: %lu\n", sizeof(union Value));  // 4
printf("sizeof int:   %lu\n", sizeof(int));           // 4
printf("sizeof float: %lu\n", sizeof(float));         // 4

The union is 4 bytes — not 12. All three members share that same 4-byte block.

When to Use Unions

  • Variant types — a value that could be an int, float, or string depending on context
  • Hardware registers — accessing the same bits as different types
  • Parsers — interpreting the same data in multiple ways
  • Memory savings — when you only need one field at a time

Full Code

#include <stdio.h>

union Value {
  int i;
  float f;
  char c;
};

int main() {
  union Value v;

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

  v.f = 3.14;
  printf("float: %.2f\n", v.f);
  printf("int after float: %d (garbage)\n", v.i);

  printf("\nsizeof union: %lu\n", sizeof(union Value));
  printf("sizeof int:   %lu\n", sizeof(int));
  printf("sizeof float: %lu\n", sizeof(float));

  return 0;
}

Compile and run:

gcc unions.c -o unions
./unions

Next episode: Typedef — custom type names for cleaner code.

Student code: github.com/GoCelesteAI/c-in-100-seconds/episode25