Wherever you use constants, you can use enumerations. In addition, enumerations can be use to tag switch cases with a name for easier readability. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
enum Switch_Labels
{
A_RED_CAR_WITH_ALLOYS = 0,
A_BLUE_CAR_WITH_ALLOYS = 1
};
Switch_Labels Value_(...);
switch(Value_)
{
case A_RED_CAR_WITH_ALLOYS:
// ...
case A_BLUE_CAR_WITH_ALLOYS:
// ...
}
|
As you can see, the labels are much more descriptive and to the point than magic constants.
Another use of enumerations is providing the ability to create a ranged-value variable. An instance of "
Switch_Labels", for example, can only hold the enumerators that pertain to the "
Switch_Labels" enumeration. This can be useful for tagging certain indices of an array. For instance:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
enum Wheel_Index
{
WHEEL_FRONT_LEFT = 0,
WHEEL_FRONT_RIGHT = 1,
WHEEL_REAR_LEFT = 2,
WHEEL_REAR_RIGHT = 3
};
Wheel_Class Wheels_[4];
Wheel_Index Index_(WHEEL_FRONT_RIGHT);
// In some function:
Wheels_[WHEEL_FRONT_RIGHT] = ...;
|
By using enumerators, we can clearly see which wheel we're accessing. If we used magic constants, we would have to guess which wheel we're referring to.
Other uses of enumerations are replacing pre-processor constants and bit-masks. For example:
1 2 3 4 5 6 7 8 9
|
enum Parameters
{
PARAM_LIKES_TV = (1 << 0),
PARAM_LIKES_GAMING = (1 << 1),
PARAM_HATES_CSHARP = (1 << 2),
// ...
};
Parameters Params_(PARAM_LIKES_GAMING | PARAM_HATES_CSHARP);
|
There are probably more uses, but these are the most common.
Wazzak