Question

Sorry if the question may be very stupid: I have an enum and the name contained in the enum must be a number:

enum class EE
{
    ZERO,
    ONE,
    TWO,
    // ...
}

enum class EE2
{
    _0,
    _1,
    _2,
    // and so on ...
};

If i remember well the undercorse in front of names must be reserved to implementation. But which is the preferred way to sepcify a number inside an enum?

Let's have a more concrete example: I can write for example:

enum JoysticButton
{
    BUTTON_1,
    BUTTON_2,
    // AND SO ON
};

But to use the enum I have to write:

if ( k == JoysticButton::BUTTON_1 )

And this is very much verbose. Or.

enum JoysticButton
{
    _1,
    _2,
    // AND SO ON
};

if ( k == JoysticButton::_1 )

But the second alternative is less clear

Was it helpful?

Solution 3

But which is the preferred way to sepcify a number inside an enum?

The prefer way is to be specific, and name the enum and it's values as clearly as possible. It all depends what the enum represents.

For example, if the number represents a version, then something like this (btw EE is an awful generic name) :

enum class EE
{
    v_1,
    v_1_1,
    v_2,
    v_3,
    // ...
};

OTHER TIPS

Only underscores followed by a capital letter or another underscore are reserved for the implementation, so you're free to use _1, _2, etc.

Why using an enum class in the first place?

In this case, a plain old enum is the clearest, I think:

enum JoysticButton
{
    JoysticButton1,
    JoysticButton2,
    // ...
};

if ( k == JoysticButton1 ) ...

The default enum type is int. You can do this, I believe this is what you are asking.

enum class EE
{
    ONE = 1,
    TWO = 2,
    // ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top