Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to use enum as int?

Tags:

c++

enums

int

So, I have a variable "state" in a class. I want to declare it as an integer so I can save some if statements.

int state;

One way to do this is to declare an enum State {One = 0, Two = 1, Three = 3}, and then in the switch statement, it would become:

switch (state)
{
case One:
    dosomething();
    break;
case Two:
    dosomething();
    break;
case Three:
    dosomething();
    break;
}

So, is it a good practice to use enum like this? Is there a better way to do this?

Thanks!

like image 1000
Snowfish Avatar asked Feb 10 '11 21:02

Snowfish


1 Answers

Yes that is a good way to do it. You generally use enums to make life easier, a lot of different numbers that don't really tell other coders anything isn't quite helpful.

So this is a perfectly good way of using it, it makes your code readable and understandable.

Altough as @James McNellis pointed out, naming your enums like "1,2,3,4" is a bad idea, since it doesn't express what it really does.

But I suspect that was only an example from your side.

Consider this instead:

switch (operationState)
{
    case Waiting:
        dosomething();
        break;
    case Running:
        dosomething();
        break;
    case Ended:
        dosomething();
        break;
}

In this case, the "operation" is either: Waiting, Running or Ended, which makes it readable and understandable. Now consider the way without enums:

switch (iState)
{
    case 997:
        dosomething();
        break;
    case 998:
        dosomething();
        break;
    case 999:
        dosomething();
        break;
}

What does 997 tell you? Absolutely Nothing! Use readable and understandable code to make everyones life easier.

like image 168
Filip Ekberg Avatar answered Nov 08 '22 14:11

Filip Ekberg