Initialization of enumerations

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

C++ In C++, the initializer must have the same type as the associated enumeration type.

The first line of the following example declares the enumeration 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;

C++ Beginning of C++11 only.

The following rules apply to both the scoped and unscoped enumerations.

  • An enumeration cannot be initialized using an integer or enumeration constant from a different enumeration, without an explicit cast.
  • An uninitialized enumeration variable has undefined value.

The following statement declares an unscoped enumeration color.

enum color { white, yellow, green, red, brown };

The following statement declares a scoped enumeration letter and references the scoped enumerators directly inside the scope of the enumeration. The initial values of A, B, C, and D are 0, 1, 1, and 2.

enum class letter { A, B, C = B, D = C + 1 };

The following statement defines a variable let1 and initializes let1 to the value of A. The integer value associated with A is 0.

letter let1 = letter :: A;

To reference scoped enumerators outside of the enumeration's scope, you must qualify the enumerators with the name of the enumeration. For example, the following statement is invalid.

letter let2 = A;     //invalid

The keyword enum in the following statement is optional and can be omitted.

enum letter let3 = letter :: B;

The white enumerator is visible in the following statement, because color is an unscoped enumeration.

color color1 = white;     // valid

Unscoped enumerations can also be qualified with their enumeration scope, for example:

color color2 = color :: yellow;    // valid

You cannot initialize an enumeration with an enumeration constant from a different enumeration or an integer without an explicit cast. For example, the following two statements are invalid.

letter let4 = color :: white;   // invalid

letter let5 = 1;                // invalid

You can use explicit cast to initialize an enumeration with an enumeration constant from a different enumeration or an integer. For example, the following two statements are valid.

letter let6 = (letter) color :: white;     // valid

letter let7 = (letter) 2;                  // valid

C++ End of C++11 only.