5 ms·
My favourite trick with designated initialisers is using them with array indices and enums, e.g. enum color {RED, GREEN, BLUE}; char *color_name[] = {
by snops 7y ago
My favourite trick with designated initialisers is using them with array indices and enums, e.g.
enum color {RED, GREEN, BLUE};
char *color_name[] = {
[RED] = "Red",
[GREEN] = "Green",
[BLUE] = "Blue"
};
printf("%s",color_name[RED]);
This means you don't have to ensure ordering is the same between the enum and the array, which can be a pain for more complex tables. It's a shame C++ doesn't support this, more details: https://eli.thegreenplace.net/2011/02/15/array-initialization-with-enum-indices-in-c-but-not-c https://eli.thegreenplace.net/2011/02/15/array-initializatio...