Compound Literal in C

Level 5291 keystrokes

Uses compound literals, unnamed objects written as (type){initializers}, to pass Point values straight to a function, once in order and once with designated initializers. It also creates an unnamed int array in place and prints Point: (10, 20), Point: (40, 50) and 1 2 3 4 5.

C code

// A point with two int coordinates
1struct Point {
2 int x, y;
3};
4
// Receives a copy of the Point and prints it
5void printPoint(struct Point p) {
6 printf("Point: (%d, %d)\n", p.x, p.y);
7}
8
// (struct Point){10, 20} builds an unnamed Point on the spot: prints Point: (10, 20)
9printPoint((struct Point){10, 20});
// With .member = value the order does not matter: prints Point: (40, 50)
10printPoint((struct Point){.y = 50, .x = 40});
11
// An unnamed array created in place; it decays to a pointer to its first element
12int *arr = (int[]){1, 2, 3, 4, 5};
// Prints its elements: 1 2 3 4 5
13for (int i = 0; i < 5; i++) {
14 printf("%d ", arr[i]);
15}
// Ends the output line
16printf("\n");

Output

Point: (10, 20)
Point: (40, 50)
1 2 3 4 5
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.

  • ,× 11
  • (× 11
  • )× 11
  • ;× 10
  • "× 6
  • {× 6
  • }× 6
  • .× 4
  • =× 4
  • %× 3

More C examples at level 5

← C typing practice