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 d
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;