0 day streak
c / intermediate
Snippet

Designated Initializers for Structures

Designated initializers allow you to initialize structure members by name rather than by position. This makes code more robust against changes in the structure definition and improves readability by explicitly stating which value belongs to which field.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
struct Config {
int timeout;
float threshold;
char mode;
};
int main() {
// Initialize specific members out of order
struct Config sys_cfg = {
.mode = 'A',
.timeout = 3600,
.threshold = 0.85f
};
printf("Mode: %c, Timeout: %d\n", sys_cfg.mode, sys_cfg.timeout);
return 0;
}
Breakdown
1
.mode = 'A',
Explicitly assigns 'A' to the 'mode' member using the dot operator.
2
struct Config sys_cfg = { ... };
Initializes the struct instance in a single, clear block.