作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
假设我有一些在我的程序中经常使用的字符串(用于存储状态和类似的东西)。字符串操作可能很昂贵,所以每当处理它们时我都想使用枚举。到目前为止,我已经看到了几个解决方案:
typedef enum {
STRING_HELLO = 0,
STRING_WORLD
} string_enum_type;
// Must be in sync with string_enum_type
const char *string_enumerations[] = {
"Hello",
"World"
}
另一个我经常遇到的:
typedef enum {
STRING_HELLO,
STRING_WORLD
} string_enum_type;
const char *string_enumerations[] = {
[STRING_HELLO] = "Hello",
[STRING_WORLD] = "World"
}
这两种方法的优缺点是什么?还有更好的吗?
最佳答案
前者的唯一优势是它向后兼容古老的 C 标准。
除此之外,后一种选择更为优越,因为即使枚举被修改或项目位置发生变化,它也能确保数据完整性。然而,它应该通过检查来完成,以确保枚举中的项目数与查找表中的项目数相对应:
typedef enum {
STRING_HELLO,
STRING_WORLD,
STRING_N // counter
} string_enum_type;
const char *string_enumerations[] = {
[STRING_HELLO] = "Hello",
[STRING_WORLD] = "World"
};
_Static_assert(sizeof string_enumerations/sizeof *string_enumerations == STRING_N,
"string_enum_type does not match string_enumerations");
以上是简单“枚举-查找表”耦合的最佳方法。另一种选择是使用结构,但这更适合更复杂的数据类型。
最后,作为旁注,第三个版本将使用“X 宏”。除非您对代码重复和维护有特殊要求,否则不建议这样做。为了完整起见,我将其包含在此处,但我不建议在一般情况下使用它:
#define STRING_LIST \
/* index str */ \
X(STRING_HELLO, "Hello") \
X(STRING_WORLD, "World")
typedef enum {
#define X(index, str) index,
STRING_LIST
#undef X
STRING_N // counter
} string_enum_type;
const char *string_enumerations[] = {
#define X(index, str) [index] = str,
STRING_LIST
#undef X
};
_Static_assert(sizeof string_enumerations/sizeof *string_enumerations == STRING_N,
"string_enum_type does not match string_enumerations");
关于c - 将枚举与字符串相关联的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48986498/
现在我正在尝试实现 flash programming specification对于 PIC32MX。我正在使用 PIC32MX512L 和 PIC32MX512H。 PIC32MX512L最终必须
我是一名优秀的程序员,十分优秀!