3 ms·
Foreach macros. Nice when you have a list of constant that you need for declaring a lot of tables or enumerations. Here an example with ISO-639 language codes
by gallier2 6y ago
Foreach macros. Nice when you have a list of constant that you need for declaring a lot of tables or enumerations. Here an example with ISO-639 language codes
Example with 3 "values". This is the base definition from which all the tables and enums are produced.
#define FOREACH_LAN(LAN)\
LAN(GA, IE, C_ANSI ) /**< Irish Gaelic : 0 */ \
LAN(DE, DE, C_ANSI ) /**< German : 1 */ \
LAN(DA, DA, C_ANSI ) /**< Danish : 2 */ \
LAN(EL, EL, C_GREEK ) /**< Greek : 3 */ \
LAN(EN, GB, C_ANSI ) /**< English : 4 */ \
LAN(ES, ES, C_ANSI ) /**< Spanish : 5 */
etc.
Let's define an enum indexing with these languages
#define GENERATE_LANIDX(lan,country,codepage) LANIDX_ ## lan,
typedef enum {
LANIDX_UNDEFINED = -1, //
FOREACH_LAN(GENERATE_LANIDX)
LANIDX_MAX // Automatically get the upper bound
} LANIDX_TYPE;
This is equivalent to
typedef enum {
LANIDX_UNDEFINED = -1, //
LANIDX_GA,
LANIDX_DE,
LANIDX_DA,
LANIDX_EL,
LANIDX_EN,
LANIDX_ES,
LANIDX_MAX // Automatically get the upper bound
} LANIDX_TYPE;
but I didn't need to repeat all the language codes, the macro did it for us.
Now in the module I can define tables, also without needing to repeat the codes
const char *LanIdx2LanTable[] = {
#define GENERATE_LANIDDX_2_LAN(lan,country,codepage) [1+ LANIDX_ ## lan]={#lan},
FOREACH_LAN(GENERATE_LANIDDX_2_LAN)
};
const char *LanIdx2CodePageTable[] = {
#define GENERATE_LANCP(lan,country,codepage) [1+LANIDX_ ## lan]=codepage,
FOREACH_LAN(GENERATE_LANCP)
};