Union Size in C

Level 4187 keystrokes

Shows that union size equals its largest member and only one member is valid at a time.

C code

// Union where all members share same memory
1union Value {
2 char c;
3 int i;
4 double d;
5};
6
// Create union variable
7union Value v;
// Union size is size of largest member (double = 8)
8printf("Union size: %lu\n", sizeof(union Value));
// Store a double value
9v.d = 3.14159;
// %f prints 6 decimal places: 3.141590
10printf("Double: %f\n", v.d);
// Storing int overwrites the double
11v.i = 42;
// Only i is valid now; reading v.d would not give 3.14159
12printf("Int: %d\n", v.i);

Output

Union size: 8
Double: 3.141590
Int: 42
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
  • "× 6
  • .× 5
  • (× 4
  • )× 4
  • ,× 3
  • :× 3
  • \× 3
  • %× 3
  • =× 2

More C examples at level 4

← C typing practice