Stefan Rendevski
Stefan Rendevski

Reputation: 329

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?

Upvotes: 0

Views: 1341

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

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;

Upvotes: 1

user1350184
user1350184

Reputation:

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;

Upvotes: 2

Related Questions