Designated Initializers in C

Level 4230 keystrokes

Initializes a struct Config with designated initializers (.port, .retries, .timeout), which set members by name in any order, then prints the three values 8080, 30 and 3.

C code

// Defines a configuration struct with three int members
1struct Config {
// Members in declaration order: port, timeout, retries
2 int port;
3 int timeout;
4 int retries;
5};
6
// Designated initializers name each member with the .member syntax
// They can be listed in any order; any member left out would be 0
7struct Config cfg = {
8 .port = 8080,
// retries is set before timeout, unlike the declaration order
9 .retries = 3,
10 .timeout = 30
11};
// Each value went to the named member; prints Port: 8080
12printf("Port: %d\n", cfg.port);
// Prints Timeout: 30
13printf("Timeout: %d\n", cfg.timeout);
// Prints Retries: 3
14printf("Retries: %d\n", cfg.retries);

Output

Port: 8080
Timeout: 30
Retries: 3
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
  • .× 6
  • "× 6
  • ,× 5
  • =× 4
  • :× 3
  • (× 3
  • )× 3
  • \× 3
  • %× 3

More C examples at level 4

← C typing practice