An enumeration is a user-defined data type whose values consist of a set of named constants. In C++, you declare an enumeration with the enum keyword, just as in C. The only difference between enumerations in the two languages is that in C, declarations of instances of an enumeration must include the enum keyword. In C++, an enumeration becomes a data type when you define it. Once defined, it is known by its identifier alone (the same as any other type) and declarations can use the identifier name alone.
The following example demonstrates how a C++ program can reference an enumeration by using the identifier without the enum qualifier.
// enum as a data type
#include <iostream.h>
enum color { red, orange, yellow, green, blue, violet };
void main()
{
color myFavorite;
myFavorite = blue;
}
Notice that the declaration of myFavorite uses only the identifier color; the enum keyword is unnecessary. Once color is defined as an enumeration, it becomes a new data type. (In later chapters, you'll see that classes have a similar property. When a class is defined, it becomes a new data type.)
Each element of an enumeration has an integer value, which, by default, is one greater than the value of the previous element. The first element has the value 0, unless you specify another value. You can also specify values for any subsequent element, and you can repeat values. For example:
enum color { red, orange, yellow, green, blue, violet );
// Values: 0, 1, 2, 3, 4, 5
enum day { sunday = 1, monday,
tuesday, wednesday = 24,
thursday, friday, saturday };
// Values: 1, 2, 3, 24, 25, 26, 27
enum direction { north = 1,south,
east = 1, west };
// Values: 1, 2, 1, 2
You can convert an enumeration into an integer. However, you cannot perform the reverse conversion unless you use a cast. For example:
color myFavorite, yourFavorite;
int i;
myFavorite = blue;
i = myFavorite; // Legal; i = 4
yourFavorite = 5; // Error: cannot convert
// from int to color
myFavorite = (color)4; // Legal
Explicitly casting an integer into an enumeration is generally not safe. If the integer is outside the range of the enumeration, or if the enumeration contains duplicate values, the result of the cast is undefined.