c - 枚举数据类型转换为int类型?

标签 c initialization translate

我对 C 很陌生,我得到了以下说明:

“将枚举数据类型 dfaState 转换为 int 类型;因此,变量 state 应该是 int 变量。另外,将枚举值 EE、OE、OO 和 EO 分别映射到整数常量 0、1、2 和 3。”

这是我得到的代码:

#include <stdio.h>
enum dfaState { EE, OE, OO, EO };
enum dfaState state = EE;
char input;

int main(void)
{
    //main function here
}

我应该如何处理这些说明?我试过这个:

#include <stdio.h>
int EE = 0;
int OE = 1;
int OO = 2;
int EO = 3;
int state;
char input;

int main(void)

但我收到错误。如有任何帮助,我们将不胜感激。

最佳答案

来自 C11 标准:

C11 (n1570), § 6.7.2.2 Enumeration specifiers

Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.

这意味着在 C 中,枚举基础类型已经是整型:您的代码已经执行了它应该执行的操作:您可以更明确地分别使用值 0、1、2、3:

#include <stdio.h>

enum dfaState {
  EE = 0,
  OE = 1,
  OO = 2,
  EO = 3
};
enum dfaState state = EE;

int main(void) {
  printf("dfaState %d\n", state); // will print "0"
  return 0;
}

关于c - 枚举数据类型转换为int类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33227581/

相关文章:

在 C 中释放内存的说明

c - 在下面的场景中我是服务器还是客户端?

javascript - AEM 6.x : How to access i18n translations via Javascript?

eclipse - 将 Google Translate Eclipse 插件集成到 eclipse

c 程序将函数参数中的括号解释为第二个函数

c - 如果我之前输入了某个输入,为什么 scanf() 不等待下一个输入

c - 为什么灵活数组成员的静态初始化有效?

c++ - 静态变量声明和定义

C++ 构造函数错误。无法初始化字符串数组

java - 在 Java 中翻译异常消息