Conversions and Enumerated Types

Because enumerated types are integral types, any enumerator can be converted to another integral type by integral promotion. Consider this example:

enum Days

{

Sunday,

Monday,

Tuesday,

Wednesday,

Thursday,

Friday,

Saturday

};

int i;

Days d = Thursday;

i = d; // Converted by integral promotion.

cout << “i = ” << i << “\n”;

However, there is no implicit conversion from any integral type to an enumerated type. Therefore, (continuing with the preceding example) the following statement is in error:

d = 6; // Erroneous attempt to set d to Saturday.

Assignments such as the one above, where no implicit conversion exists, must use a cast to perform the conversion:

d = (Days)6; // Explicit cast-style conversion to type Days.

d = Days( 4 ); // Explicit function-style conversion to type Days.

The example above shows conversions of values that coincide with the enumerators. There is no mechanism that protects you from converting a value that does not coincide with one of the enumerators. For example:

d = Days( 967 );

Some such conversions may work. However, there is no guarantee the resultant value will be one of the enumerators. Additionally, if the size of the enumerator is too small to hold the value being converted, the value stored may not be what you expect.