【发布时间】:2017-02-05 02:59:56
【问题描述】:
我想防止无效值枚举分配。我知道如果我什至分配不在枚举中的值,它就会起作用。示例:
enum example_enum
{
ENUM_VAL0,
ENUM_VAL1,
ENUM_VAL2,
ENUM_VAL3
};
void example_function(void)
{
enum example_enum the_enum = ENUM_VAL3; // correct
the_enum = 41; // will work
the_enum = 0xBADA55; // also will work
bar(the_enum); // this function assumes that input parameter is correct
}
是否有简单有效的方法来检查对枚举的分配是否正确?我可以按功能测试值
void foo(enum example_enum the_enum)
{
if (!is_enum(the_enum))
return;
// do something with valid enum
}
我可以通过以下方式解决这个问题:
static int e_values[] = { ENUM_VAL0, ENUM_VAL1, ENUM_VAL2, ENUM_VAL3 };
int is_enum(int input)
{
for (int i=0;i<4;i++)
if (e_values[i] == input)
return 1;
return 0;
}
对我来说,我的解决方案效率低下,如果我有更多的枚举和枚举中的更多值,我该怎么写?
【问题讨论】:
-
编译器警告?
-
使用断言。在 C 中,
enums 实际上是int。 C 不是 C++。
标签: c testing enums compile-time compile-time-constant