简体   繁体   中英

Enum type variable declarations in C

I declared this enum type in C :

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

When I try to create a variable of type months in main() with:

months month;

It gives the following error:

unknown type 'months'

But when I declare it like this:

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

It works fine. I thought both ways were valid, so why is there an error?

You need to wrap a typedef around it, otherwise you can access it by stating that it's an enum .

Example:

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

Or

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

Instead of

months month;

you have to write

enum months month;

The other way is to define a typedef for the enumeration. For example

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

and then you may write

months month;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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