Designated initializers in C
C99 lets you name the members and elements you are initializing.
struct Settings {
int time_limit;
int editor_mode;
const char *theme;
};
struct Settings defaults(void) {
struct Settings s = {.time_limit = 60, .theme = "default"};
return s;
}
int sparse_sum(void) {
int weights[8] = {[0] = 5, [3] = 10, [7] = 1};
int total = 0;
for (int i = 0; i < 8; i++) {
total += weights[i];
}
return total;
}
How it works
- Naming a field makes the initializer survive a reordering.
- Anything not named is zero-initialized.
- Array designators skip ahead, leaving the gaps at zero.
Keywords and builtins used here
Settingscharconstforintreturnstructvoid
The run, in numbers
- Lines
- 19
- Characters to type
- 333
- Tokens
- 111
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 74 seconds.
Step 3 of 4 in Values & storage, step 29 of 35 in Language basics.