Union Type in C

Level 4117 keystrokes

Demonstrates union where all members share the same memory location.

C code

// Union members share the same memory; its size is that of the largest member
1union Data {
2 int i;
3 float f;
4 char c;
5};
6
// Create a union variable
7union Data d;
// Store 65 as integer (ASCII for 'A')
8d.i = 65;
// Access as integer shows 65
9printf("int: %d\n", d.i);
// c reads the first byte of i: 'A' on little-endian machines such as x86
10printf("char: %c\n", d.c);

Output

int: 65
char: A
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ;× 8
  • "× 4
  • .× 3
  • ,× 2
  • :× 2
  • (× 2
  • )× 2
  • \× 2
  • %× 2
  • {× 1

More C examples at level 4

← C typing practice