Is this a valid listing, and if so, why?

enum color = {blue, black=3, yellow=3};

      

2 colors matter 3, is it really? I thought the enum should have different meanings.

+3


source to share


5 answers


This is permissible in that it is permitted. This is probably not a very good design.

As I understand it, I'm not sure what answer you are looking for there. If this was not allowed, then it would prevent cases where it made sense to have two enums referring to the same value. (I'm sure I could easily come up with examples where this made sense.)



So, if it's a choice between limiting what I can do or limiting because I usually don't want duplicates, then I would vote as it is.

+9


source


The C ++ standard , section 7.2, part 1, only requires a constant expression to be an integral or numbered type; the constant values ​​do not need to be different from each other. This gives you additional flexibility in flattening your constants if you think it makes your code more expressive. For example,

enum color {red=1,green=2,blue=3,max_color=3};

if (myColor > max_color) {/* report an error *}

      



better than

enum color {red=1,green=2,blue=3};

if (myColor > blue) {/* report an error *}

      

+2


source


Let's say you've designed a structure. This structure uses an enum for parameterization

For some reason, you are no longer happy with the previously used term.

Simply replacing the term would break existing software. You have decided to propose old and new terminology (for at least one release cycle).

0


source


#include <iostream>

using namespace std;

enum color {blue, black=3, yellow=3};

int main()
{

    color a = blue;
    color b = black;
    color c = yellow;
    cout<<a<<endl;
    cout<<b<<endl;
    cout<<c<<endl;


        return 0;
}

      

It's nice to make them the same.

0


source


Yes, it really is. Because it doesn't violate the language specification. In the N3242 project, as shown in the example, the value associated with another enumerator does not have to be different:

The identifiers in an enumerator-list are declared as constants, 
and can appear wherever constants are required. An enumeratordefinition
with = gives the associated enumerator the value indicated by the 
constant-expression. The constant-expression shall be an integral 
constant expression (5.19). If the first enumerator has no initializer,
the value of the corresponding constant is zero. An enumerator-definition without
an initializer gives the enumerator the value obtained by
increasing the value of the previous enumerator by one.
[ Example:
enum { a, b, c=0 };
enum { d, e, f=e+2 };
defines a, c, and d to be zero, b and e to be 1, and f to be 3. —end example ]

      

0


source







All Articles