Defining Enumeration Variables

An enumeration variable definition contains an optional storage class specifier, a type specifier, a declarator, and an optional initializer. The type specifier contains the keyword enum followed by the name of the enumeration data type. You must declare the enumeration data type before you can define a variable having that type.

The initializer for an enumeration variable contains the = symbol followed by an expression.

In C, the initializer expression must evaluate to an int value. In C++ , the initializer must be have the same type as the associated enumeration type

The first line of the following example declares the enumeration tag grain. The second line defines the variable g_food and gives g_food the initial value of barley (2).

enum grain { oats, wheat, barley, corn, rice };
enum grain g_food = barley;

In C, the type specifier enum grain indicates that the value of g_food is a member of the enumerated data type grain. In C++, the value of g_food has the enumerated data type grain.

C++ also makes the enum keyword optional in an initialization expression like the one in the second line of the preceding example. For example, both of the following statements are valid C++ code:

enum grain g_food = barley;
     grain cob_food = corn;