Designated Initializer in C

Level 5273 keystrokes

Initializes a Config struct with designated initializers, which name each member (.id, .name, .rate, .flags) so the order need not follow the declaration. It prints ID: 100, Name: Server, Flags: 7 and Rate: 1.5.

C code

// A configuration record with four members
1struct Config {
// Numeric identifier
2 int id;
// Name stored in a char array
3 char name[20];
// Option bits stored as an int
4 int flags;
// A floating-point rate
5 double rate;
6};
7
// Each .member = value names its target, so the order is free
8struct Config cfg = {
// Sets id to 100
9 .id = 100,
// A string literal can initialize the char array directly
10 .name = "Server",
// rate comes before flags here, unlike in the declaration
11 .rate = 1.5,
// Sets flags to 7 (binary 111)
12 .flags = 7
13};
14
// Prints ID: 100, Name: Server, Flags: 7 and Rate: 1.5 (%.1f shows one decimal)
15printf("ID: %d\n", cfg.id);
16printf("Name: %s\n", cfg.name);
17printf("Flags: %d\n", cfg.flags);
18printf("Rate: %.1f\n", cfg.rate);

Output

ID: 100
Name: Server
Flags: 7
Rate: 1.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.

  • ;× 10
  • .× 10
  • "× 10
  • ,× 7
  • =× 5
  • :× 4
  • (× 4
  • )× 4
  • \× 4
  • %× 4

More C examples at level 5

← C typing practice