C Designated Initializer
C Designated Initializers is a feature which was introduced in the C99 standard.
The problem
It is quite common in C programs, to include an array of strings:
// Strings for debug
char *str[] = {
"Program start",
"Some stuff happened",
"Some other stuff happened",
"Disastrous error",
"Program end"
};
These strings can now be used throughout the program by referencing the array element.
printf("%s\n", str[0]);
With only a few strings, this can be managed, but it is quite obvious that as the list grow longer, it will become unmanageable, and also statements like: "printf("%s\n", str[0]);" are not very readable.
To make the code more readable, it is common to include an enum or defines to refer to the array element.
typedef enum {
STR_START = 0,
STR_STUFF = 1,
STR_OTHER = 2,
STR_DISASTER = 3,
STR_END = 4
} str_idx_t;
// Strings for debug
char *str[] = {
"Program start",
"Some stuff happened",
"Some other stuff happened",
"Disastrous error",
"Program end"
};
The strings can now be referred like:
printf("%s\n", str[STR_START]);
Which is obviously much more readable.
Synchronization between the enum and the array is still the responsibility of the programmer, and as the list grow long, errors can and will creep in.
The solution: Designated Initializer
The solution to the synchronization problem, was introduced in C99 as Designated Initializers. With those, the above piece of code can be rewritten as:
typedef enum {
STR_START = 0,
STR_STUFF = 1,
STR_OTHER = 2,
STR_DISASTER = 3,
STR_END = 4
} str_idx_t;
// Strings for debug
char *str[] = {
[STR_START] = "Program start",
[STR_STUFF] = "Some stuff happened",
[STR_OTHER] = "Some other stuff happened",
[STR_DISASTER] = "Disastrous error",
[STR_END] = "Program end"
};
The order of the strings in the array as written is no longer relevant as they will be sorted following the enum. Also if there are "holes" (undefined strings" it will result in a NULL string in the array,
Video
C Designated Initializers were covered in a STM32World short video:
Miscellaneous links
To be added