Union Type in C

Level 5169 keystrokes

Declares a union whose int, float and char members share the same memory. After storing 65 in the int, reading the char gives 'A' on little-endian machines; storing 3.14f then overwrites those bytes and prints 3.14.

C code

// In a union all members start at the same address and share one memory area
1union Data {
// Three views of those bytes; the union is as large as its largest member
2 int i;
3 float f;
4 char c;
5};
6
// Declares a variable of the union type
7union Data d;
// Writes 65 through the int member
8d.i = 65;
// Prints As int: 65
9printf("As int: %d\n", d.i);
// Reads the first byte as a char: on little-endian machines that byte is 65, which is 'A' in ASCII
10printf("As char: %c\n", d.c);
// Writing the float overwrites the same bytes, so the int value is gone
11d.f = 3.14f;
// Prints As float: 3.14 (two decimals with %.2f)
12printf("As float: %.2f\n", d.f);

Output

As int: 65
As char: A
As float: 3.14
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.

  • ;× 10
  • .× 7
  • "× 6
  • ,× 3
  • :× 3
  • (× 3
  • )× 3
  • \× 3
  • %× 3
  • =× 2

More C examples at level 5

← C typing practice