Learn C++ - C++ Enumerations

The C++ enum type creates symbolic constants.

For example, consider the following statement:

enum my_paint {red, orange, yellow, green, blue, violet, indigo, ultraviolet};

The code above makes my_paint the name of a new type; my_paint is termed an enumeration, much as a struct variable is called a structure.

It establishes red, orange, yellow, and so on, as symbolic constants for the integer values 0?7.

These constants are called enumerators.


By default, enumerators are assigned integer values starting with 0 for the first enumerator, 1 for the second enumerator, and so forth.

You can override the default by explicitly assigning integer values.

You can use an enumeration name to declare a variable of the enumeration type:

my_paint band;  // band a variable of type my_paint

The valid values for an enumeration variable without a type cast are the enumerator values used in defining the type.

band = blue;       // valid, blue is an enumerator

Thus, a my_paint variable is limited to just eight possible values.

You can assign an int value to an enum, provided that the value is valid and that you use an explicit type cast:

band = my_paint(3);         // typecast 3 to type my_paint 

Setting Enumerator Values

You can set enumerator values explicitly by using the assignment operator:

enum bits{one = 1, two = 2, four = 4, eight = 8};

The assigned values must be integers.You also can define just some of the enumerators explicitly:

enum bigstep{first, second = 100, third};

In this case, first is 0 by default. Subsequent uninitialized enumerators are larger by one than their predecessors.

So, third would have the value 101.

Finally, you can create more than one enumerator with the same value:

enum {zero, null = 0, one, numero_uno = 1};

Here, both zero and null are 0, and both one and numero_uno are 1.