Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two enums have some elements in common, why does this produce an error?

Tags:

c++

c

enums

I have two enums in my code:

enum Month {January, February, March, April, May, June, July,         August, September, October, November, December}; enum ShortMonth {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}; 

May is a common element in both enums, so the compiler says:

Redeclaration of enumerator 'May'.

Why does it say so? And how can I circumvent this?

like image 896
Pieter Avatar asked Jan 29 '10 12:01

Pieter


People also ask

Can two enum names have the same value?

1. Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

Can we add constants to enum without breaking existing code?

4) Adding new constants on Enum in Java is easy and you can add new constants without breaking the existing code.

What is the point of enums?

The entire point of enums are to make your code more readable. They are not casted to ints, since they are by default ints. The only difference is instead of going back and forth checking what int values you may have, you can have a clear set of enums to make the code more readable.

What is the point of enums in C?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.


2 Answers

Enum names are in global scope, they need to be unique. Remember that you don't need to qualify the enum symbols with the enum name, you do just:

Month xmas = December; 

not:

Month xmas = Month.December;  /* This is not C. */ 

For this reason, you often see people prefixing the symbol names with the enum's name:

enum Month { Month_January, Month_February, /* and so on */ }; 
like image 150
unwind Avatar answered Sep 19 '22 20:09

unwind


I suggest you merge the two:

enum Month {   Jan, January=Jan, Feb, February=Feb, Mar, March=Mar,    Apr, April=Apr,   May,               Jun, June=Jun,    Jul, July=Jul,    Aug, August=Aug,   Sep, September=Sep,    Oct, October=Oct, Nov, November=Nov, Dec, December=Dec}; 

Which will have exactly the same effect, and is more convenient.

If you want January to have the value 1, instead of 0, add this:

enum Month {   Jan=1, January=Jan, Feb, February=Feb, .... 
like image 39
Alex Brown Avatar answered Sep 19 '22 20:09

Alex Brown