ENUMERATIONS

closed account (LN7oGNh0)
I know what enumerations are but I don't really understand how to use them or what I could do with them.

Could anyone give me an explanation of what they are, then show me an example of how they could be used?

Thanks.
closed account (zb0S216C)
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
Last edited on
closed account (LN7oGNh0)
Thank you
The last example will not work unless you have overloaded operator|.
closed account (zb0S216C)
@Peter87: I omitted the overload for simplicity. I assumed Hazique35 had the common sense to overload it.

Wazzak
Last edited on
Topic archived. No new replies allowed.