如果我有多个enum
,例如:
enum Greetings{ hello, bye, how };
enum Testing { one, two, three };
如何强制使用正确的enum
?
例如,我不希望有人在应该使用 one
时使用 hello
以获得更好的调试和可读性。
最佳答案
在 C 中,您可以使用样板代码伪造它。
typedef enum { HELLO_E, GOODBYE_E } greetings_t;
struct greetings { greetings_t greetings; };
#define HELLO ((struct greetings){HELLO_E})
#define GOODBYE ((struct greetings){GOODBYE_E})
typedef enum { ONE_E, TWO_E } number_t;
struct number { number_t number; };
#define ONE ((struct number){ONE_E})
#define TWO ((struct number){TWO_E})
void takes_greeting(struct greetings g);
void takes_number(struct number n);
void test()
{
takes_greeting(HELLO);
takes_number(ONE);
takes_greeting(TWO);
takes_number(GOODBYE);
}
这不应产生任何开销,并会产生错误而不是警告:
$ gcc -c -std=c99 -Wall -Wextra test2.c test2.c: In function ‘test’: test2.c:19: error: incompatible type for argument 1 of ‘takes_greeting’ test2.c:20: error: incompatible type for argument 1 of ‘takes_number’
请注意,我没有使用 GNU 扩展,也没有生成虚假警告。只有错误。另请注意,我使用的 GCC 版本非常古老,
$ gcc --version powerpc-apple-darwin9-gcc-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5493) Copyright (C) 2005 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
这应该适用于任何支持 C99 复合文字的编译器。
关于c - C 中的类型安全枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14822342/