繁体   English   中英

C中的枚举类型变量声明

[英]Enum type variable declarations in C

我在C中声明了这个枚举类型:

enum months { JAN = 1, FEB, MAR, APR, MAY, JUN,
              JUL, AUG, SEP, OCT, NOV, DEC } ;

当我尝试使用以下方法在main()创建类型为months的变量时:

months month;

它给出以下错误:

未知类型“月”

但是当我这样声明时:

enum months { JAN = 1, FEB, MAR, APR, MAY, JUN,
              JUL, AUG, SEP, OCT, NOV, DEC } month;

工作正常。 我认为这两种方法都是有效的,那么为什么会出现错误呢?

您需要在其周围包装一个typedef ,否则可以通过声明它是一个enum来访问它。

例:

typedef enum { JAN = 1, FEB, MAR, APR, MAY, JUN,
          JUL, AUG, SEP, OCT, NOV, DEC } months;
months month;

要么

enum months { JAN = 1, FEB, MAR, APR, MAY, JUN,
          JUL, AUG, SEP, OCT, NOV, DEC };
enum months month;

代替

months month;

你必须写

enum months month;

另一种方法是为枚举定义一个typedef。 例如

typedef enum months { JAN = 1, FEB, MAR, APR, MAY, JUN,
              JUL, AUG, SEP, OCT, NOV, DEC } months;

然后你可以写

months month;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM