Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning values to enum

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)

like image 610
Patrick Avatar asked Dec 26 '22 00:12

Patrick


2 Answers

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.

like image 57
Mike Seymour Avatar answered Jan 05 '23 18:01

Mike Seymour


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.

like image 45
Eric Avatar answered Jan 05 '23 18:01

Eric