While doing a review of some older code, I notice the following two strange constructions using enum (two different files/classes/namespaces, just putting them together here):
enum FirstEnum
{
A_CHOICE
,ANOTHER_CHOICE=1
,YET_SOME_OTHER_CHOICE
};
enum SecondEnum
{
FIRST_CHOICE
,SECOND_CHOICE
,THIRD_CHOICE
,DEFAULT_CHOICE=SECOND_CHOICE
};
I think both constructions are wrong.
The first one assigns a value to one of the choices, but not to the others, meaning that things might go wrong if new choices are added.
In the second case, we end up with two enumeration elements having the same underlying value.
Is there any reason why the C++ standard allows both constructions?
(using Visual Studio 2010)
The first one assigns a value to one of the choices, but not to the others, meaning that things might go wrong if new choices are added.
I don't know what you mean by "go wrong". It's well-defined that if you don't specify a value for an enumerator, its value is one more than the previous (or zero, if it's the first).
In the second case, we end up with two enumeration elements having the same underlying value.
Yes we do. That would be wrong if enumerations were supposed to be a set of unique values but (in C++) they aren't.
Is there any reason why the C++ standard allows both constructions?
Because, in C++, an enumeration is simply a way to declare a set of related, named, constant values. It doesn't try to restrict what values they can take.
This article from Microsoft should help:
http://msdn.microsoft.com/en-us/library/2dzy4k6e(v=VS.80).aspx
The first one assigns a value to one of the choices, but not to the others
By default, the first enumerator has a value of 0, and each successive enumerator is one larger than the value of the previous one, unless you explicitly specify a value for a particular enumerator.
In the second case, we end up with two enumeration elements having the same underlying value.
Enumerators needn't have unique values within an enumeration. The name of each enumerator is treated as a constant and must be unique within the scope where the enum is defined.
The article includes examples of how these features could be taken advantage of.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With