c - C 中的类型安全枚举?

标签 c enums

如果我有多个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/

相关文章:

C - 使用多线程时使用 lseek() 获得的 write() 位置不准确

c - 正确括号的最长子串

c - 字符串中相等标记之间的符号

java - 从列表中选择一个类型

java - 将泛型与实现相同接口(interface)的枚举类集合一起使用

c - C编程中Struct Tag名称的用途是什么?

c - 在 C 中使用 MPI 发送 2D 数组行 block

java - 与仅使用字符串相比,在 FSM 中使用枚举是否有好处?

java - 如何在java中将ISO代码转换为本地化度量单位?

java - Hibernate 上的字符串枚举