枚举声明出错

我有一个非常简单的c代码:

#include int main() { enum boolean{true,false}; boolean bl=false; if(bl==false) printf("This is the false value of boool\n"); boolean bl1=true; if(bl1==true) { printf("This is the true value of boool\n"); } return 0; } 

我只是试图使用枚举类型变量。但它给出以下错误:

 tryit4.c:5: error: 'boolean' undeclared (first use in this function) tryit4.c:5: error: (Each undeclared identifier is reported only once tryit4.c:5: error: for each function it appears in.) tryit4.c:5: error: expected ';' before 'bl' tryit4.c:6: error: 'bl' undeclared (first use in this function) tryit4.c:8: error: expected ';' before 'bl1' tryit4.c:9: error: 'bl1' undeclared (first use in this function) 

我没有看到任何理由。 你能解释一下它可能是什么原因吗?

声明enum boolean { true, false } ,声明一个名为enum boolean的类型。 在声明之后你必须使用的名称: enum boolean ,而不仅仅是boolean

如果你想要一个更短的名字(比如boolean ),你必须将它定义为原始全名的别名

 typedef enum boolean boolean; 

如果您愿意,可以在一个声明中声明enum boolean类型和boolean别名

 typedef enum boolean { true, false } boolean; 

在C中,有两种(实际上更多,但我保留在此)名称空间:普通标识符和标记标识符。 struct,union或enum声明引入了标记标识符:

 enum boolean { true, false }; enum boolean bl = false; 

从中选择标识符的命名空间由语法环绕指定。 在这里,它以enum为前缀。 如果要引入普通标识符,请将其放在typedef声明中

 typedef enum { true, false } boolean; boolean bl = false; 

普通标识符不需要特殊语法。 如果您愿意,也可以声明标签和普通标签。

您必须将变量声明为enum boolean类型,而不仅仅是boolean。 如果你发现写enum boolean b1 = foo();请使用typedef; 繁琐。

这样定义你的枚举真的是个好主意:

 typedef enum { False, True, } boolean; 

有几个原因:

  • truefalse (小写)可能是保留字
  • false为1且true为0可能会导致您以后出现逻辑问题

您声明枚举,但不是类型。 你想要的是什么

 typedef enum{false, true} boolean; // false = 0 is expected by most programmers 

这还有很多问题:
* truefalse是许多C编译器中的保留字
*明确使用true和false违反C中布尔表达式的一般做法,其中0表示false,任何非零表示true。 例如:

 int found = (a == b); 

编辑:这适用于gcc 4.1.2:

 [wally@zf ~]$ ./a.out This is the false value of boool This is the true value of boool [wally@zf ~]$ cat t2.c #include int main() { typedef enum {true,false} boolean; boolean bl=false; if(bl==false) printf("This is the false value of boool\n"); boolean bl1=true; if(bl1==true) { printf("This is the true value of boool\n"); } return 0; } 

像以前的答案演示一样,使用typedef:

 typedef enum { true, false } boolean; 

来自FAQ – C ++支持哪些C不包含的function列表:

bool keyword

这个常见问题解答有点不准确,最好说“C ++支持哪些C89不包含的function列表”

#include 添加到您的代码中,它将在尝试实现C99(例如gcc)的编译器上编译为C99。