枚举声明出错

maw*_*wia 3 c

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

         #include<stdio.h>
        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;
   }
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

我认为没有任何理由.你能解释一下它可能是什么原因吗?

Joh*_*itb 10

在C中,有两个(实际上更多,但我保留它)类型的命名空间:普通标识符和标记标识符.struct,union或enum声明引入了标记标识符:

enum boolean { true, false };
enum boolean bl = false;
Run Code Online (Sandbox Code Playgroud)

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

typedef enum { true, false } boolean;
boolean bl = false;
Run Code Online (Sandbox Code Playgroud)

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


Tad*_*ski 7

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


chr*_*too 7

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

typedef enum {
  False,
  True,
} boolean;
Run Code Online (Sandbox Code Playgroud)

有几个原因:

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

  • +1用于捕获以其他顺序定义问题的问题. (2认同)

AnT*_*AnT 7

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

如果您想要一个较短的名称(如同boolean),则必须将其定义为原始全名的别名

typedef enum boolean boolean;
Run Code Online (Sandbox Code Playgroud)

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

typedef enum boolean { true, false } boolean;
Run Code Online (Sandbox Code Playgroud)