Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some good example for using enums

Tags:

c++

c

enums

I learned enums when I learned C and from time to time I keep myself reminding about it and most of the time by re-reading from some source,it occurred to me that this is due to the fact I never use it in my programming,my programming interest concentrate around algorithmic problem solving so I am not sure where could I possibly use enums.

Could somebody suggest some good example where using enums is makes things much easy?

I would appreciate algorithmic examples but both of algorithmic or non-algorithmic examples are welcome.

like image 851
Quixotic Avatar asked Dec 30 '10 16:12

Quixotic


2 Answers

Imagine that you are programming a depth first search and you want to tag your edges with whether they are tree, back, forward, or cross. You could create an enum EDGE_TYPE with the four possibilities and use it to tag your edges.

like image 144
dsolimano Avatar answered Sep 22 '22 09:09

dsolimano


When describing/observing some attribute of some system you might find that attribute can have any value from a limited set. Name those values, assign each an integer value (code), collect them in an enumeration and you have defined a type of that attribute. All actions considering that attribute can now use this type.

Example: for some system we can consider its state as one of its attributes. We can observe it and say that it can be in 'uninitialized' state, state of 'initialization', 'active' or 'idle' state (feel free to add more states here...). If you want to perform some action on that system but which depends on the current state, how will you pass state information to that action (function)? You can pass strings 'uninitialized', 'initialization'...but more efficient, simple and safe from errors would be if you would pass just one integer from a set:

enum State
{
   Uninitialized,
   Initialization,
   Active,
   Idle
};

That function will have State as an argument and can use switch when deciding what to do depending on the current state:

void foo(..., const State state,...)
{
   ...
   switch(state)
   {
      case Uninitialized:
          cout << "Uninitialized" << endl;
          break;
      case Initialization:
          ...
   }
   ...
}

Using enumeration type to describe a limited set of attribute's values is safer then using a set of #defines and integer variable. E.g. if you have:

#define UNINITIALIZED  0
#define INITIALIZATION 1
#define ACTIVE         2
#define IDLE           3

and

int nState;

nothing can stop you to assign any integer value to nState:

nState = 4; // What state is 4?

If you use enumeration:

State state;

You cannot assign to it an arbitrary integer value but only an enumerator (although underlying type for enumeration is integer! - see this):

state = Active;
like image 27
Bojan Komazec Avatar answered Sep 22 '22 09:09

Bojan Komazec