WeCodeAcademy

C Unions and Bit Fields

A union stores different types in the same memory: only one is valid at a time. Bit fields pack small values into a few bits.

ExampleC
#include <stdio.h>

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

struct Flags {
  unsigned int visible : 1;
  unsigned int mode : 3;
};

int main(void) {
  union Value v;
  v.i = 65;
  printf("as int: %d, as char: %c\n", v.i, v.c);
  printf("union size: %zu\n", sizeof(union Value));

  struct Flags f = {1, 5};
  printf("visible=%u mode=%u\n", f.visible, f.mode);
  return 0;
}
Output
as int: 65, as char: A
union size: 4
visible=1 mode=5
Quick check

How many members of a union hold a valid value at once?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.