C99 中还有另一种方法,特别是如果您想要命名索引,允许例如本地化等。
enum STRINGS {
STR_THING1,
STR_THING2,
STR_THING3,
STR_THING4,
STR_WHATEVER,
STR_MAX /* Always put this one at the end, as the counting starts at 0 */
/* this one will be defined as the number of elements */
}
static const char *foo[STR_MAX] = {
[STR_THING1] = "123",
[STR_THING2] = "456",
[STR_THING3] = "789",
[STR_THING4] = "987",
[STR_WHATEVER] = "OR Something else",
};
通过使用命名初始化程序,即使枚举值发生变化,程序仍然是正确的。
for (i = STR_THING1; i<STR_MAX; i++)
puts(foo[i]);
或程序中具有命名索引的任何地方
printf("thing2 is %s\n", foo[STR_THING3]);
此技术可用于模拟资源包。声明一个enum 和几个带有语言变体的字符串数组,并在程序的其余部分使用一个指针。简单而快速(尤其是在 64 位机器上,获取常量(字符串)的地址可能相对昂贵。
编辑:sizeof foo/sizeof *foo 技术仍然适用于此。