我被限制为C(不能使用C++).我希望C有更严格的类型检查.
有没有办法在注释行上获得编译错误?如果有帮助,枚举值不能重叠.
enum hundred {
VALUE_HUNDRED_A = 100,
VALUE_HUNDRED_B
};
enum thousand {
VALUE_THOUSAND_A = 1000,
VALUE_THOUSAND_B
};
void print_hundred(enum hundred foo)
{
switch (foo) {
case VALUE_HUNDRED_A: printf("hundred:a\n"); break;
case VALUE_HUNDRED_B: printf("hundred:b\n"); break;
default: printf("hundred:error(%d)\n", foo); break;
}
}
void print_thousand(enum thousand bar)
{
switch (bar) {
case VALUE_THOUSAND_A: printf("thousand:a\n"); break;
case VALUE_THOUSAND_B: printf("thousand:b\n"); break;
default: printf("thousand:error(%d)\n", bar); break;
}
}
int main(void)
{
print_hundred(VALUE_HUNDRED_A);
print_hundred(VALUE_THOUSAND_A); /* Want a compile error here */
print_thousand(VALUE_THOUSAND_A);
print_thousand(VALUE_HUNDRED_A); /* Want a compile error here */
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Nor*_*sey 10
在C中,枚举类型与整数无法区分.很烦人.
我能想到的唯一前进方法是使用结构而不是枚举的kludgy解决方法.结构是生成性的,因此数以千计是截然不同的.如果调用约定合理(AMD64),则不会有运行时开销.
这是一个使用结构的示例,它可以获得您想要的编译时错误.Kludgy,但它有效:
#include <stdio.h>
enum hundred_e {
VALUE_HUNDRED_A = 100,
VALUE_HUNDRED_B
};
enum thousand_e {
VALUE_THOUSAND_A = 1000,
VALUE_THOUSAND_B
};
struct hundred { enum hundred_e n; };
struct thousand { enum thousand_e n; };
const struct hundred struct_hundred_a = { VALUE_HUNDRED_A };
const struct hundred struct_hundred_b = { VALUE_HUNDRED_B };
const struct thousand struct_thousand_a = { VALUE_THOUSAND_A };
const struct thousand struct_thousand_b = { VALUE_THOUSAND_B };
void print_hundred(struct hundred foo)
{
switch (foo.n) {
case VALUE_HUNDRED_A: printf("hundred:a\n"); break;
case VALUE_HUNDRED_B: printf("hundred:b\n"); break;
default: printf("hundred:error(%d)\n", foo.n); break;
}
}
void print_thousand(struct thousand bar)
{
switch (bar.n) {
case VALUE_THOUSAND_A: printf("thousand:a\n"); break;
case VALUE_THOUSAND_B: printf("thousand:b\n"); break;
default: printf("thousand:error(%d)\n", bar.n); break;
}
}
int main(void)
{
print_hundred(struct_hundred_a);
print_hundred(struct_thousand_a); /* Want a compile error here */
print_thousand(struct_thousand_a);
print_thousand(struct_hundred_a); /* Want a compile error here */
return 0;
}
Run Code Online (Sandbox Code Playgroud)