For example in C/C++, I would have the code:
typedef enum fruits{
apple,
banana,
lemon,
orange
} fruit_t;
Which would be equivalent to:
typedef enum fruits{
apple = 0,
banana = 1,
lemon = 2,
orange = 3
} fruit_t;
However, I would like the values to be negative, so they do not conflict with anything else. I could do it like this:
typedef enum fruits{
apple = -1,
banana = -2,
lemon = -3,
orange = -4
} fruit_t;
But if I would like to add another fruit, I have to assign another value, and if I put one inbetween, I have to renumber most of it. Is there an easier way of doing this?
First of all, there is no such thing as "C/C++", those are two different languages. You can't look at C as a subset of C++; some legal C code won't compile as a C++ program.
If you can use C++11, I suggest you use
enum class
, which gives you strongly typed enumerations:This way you can guarantee no clashing, because the compiler won't let you do any comparison with an integer or with a variable of a different enum type.
You can only compare against a variable of the same enum type, or use the binary scope resolution operator as in the example.
Another advantage of this
enum class
is that you can set the size of your enum. You can use any signed or unsigned integer type like this:When a type is not specified, the default
int
is assumed.Note that you need a compiler with C++11 support for this.
It is also quite common to declare the errors as usual enumerations and use the negative value of it, like:
In C you only need to number the top one and subsequent entries will be the previous entry
+1
, this is covered in the C99 draft standard section6.7.2.2
Enumeration specifiers which says (emphasis mine):and the wording is similar in the C++ draft standard section
7.2
Enumeration declarations paragraph 2.So just do something similar to the following:
I think you can order it anyway you like.
If you are not giving any value then next
enum
will take+1
of its previous value. If even fistenum
is not having any value then it will start from0
.But good practice is to have it in right order.
Start with
INT_MIN
on top like this:Per "5.2.4.2.1 Sizes of integer types " and/or "Annex E/1" of the C11 Standard
INT_MIN
is at least-32767
.INT_MIN
gets defined by including<limits.h>
.Add news ones at the top. You still have to number the topmost one.