Thuta Learning
AdvancedProgrammingbeginner

Unions

Relax. We'll talk through this in plain words — no textbook voice.

union looks similar to a struct, but all its members share the exact same memory location. That means only one member can hold a valid value at any given time. It's useful in low-level programs where you're trying to save memory.

c
#include <stdio.h>

union Data {
  int i;
  float f;
};

int main() {
  union Data data;

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

  data.f = 220.5;
  printf("data.f: %.1f", data.f);
  return 0;
}

data.i, then storing into data.f reuses the same memory, so you can no longer trust the previous value.

You should see
data.i: 10 data.f: 220.5

Info

Use a union when you need to store one type at a time, taking turns. If you need to hold a bunch of data all at once, use a struct instead.

Easy traps

  • It's a mistake to assume every union member holds a valid value at once, the way struct members do.
Unions | Thuta Learning