Enumerated Types
-
An enumerated type is a type whose values are defined by a list of constants of type int.
-
When defining an enumerated type, you can use any int values
and can have any number of constants defined.
For example, the following enumerated type defines a constant for the length of each month:
enum MonthLength { JAN_LENGTH = 31, FEB_LENGTH = 28, MAR_LENGTH = 31,
APR_LENGTH = 30, MAY_LENGTH = 31,
JUN_LENGTH = 30, JUL_LENGTH = 31,
AUG_LENGTH = 31,
SEP_LENGTH = 30, OCT_LENGTH = 31, NOV_LENGTH = 30,
DEC_LENGTH = 31};
Note:Two or more named constants can receive the same int value.
As a general rule of style, the names of enumerated values are all uppercase because they are symbolic constants.
-
The default for the first enumeration constant is 0.
The rest increase by 1 unless you set one or more of the enumeration constants.
Therefore the type definition
enum Direction { NORTH = 0, SOUTH = 1, EAST = 2, WEST = 3 };
is equivalent to
enum Direction { NORTH, SOUTH, EAST, WEST };
In the type definition:
enum MyEnum {ONE = 17, TWO, THREE, FOUR = -3, FIVE };
ONE takes the value 17, TWO takes the next int value 18,
THREE takes the next value 19 FOUR takes -3, and FIVE takes the next value, -2 .
The above MonthLength enumerated type can also be defined as:
enum MonthLength { JAN_LENGTH = 31, FEB_LENGTH = 28, MAR_LENGTH = 31,
APR_LENGTH = 30, MAY_LENGTH,
JUN_LENGTH = 30, JUL_LENGTH,
AUG_LENGTH = 31,
SEP_LENGTH = 30, OCT_LENGTH, NOV_LENGTH = 30,
DEC_LENGTH};
-
Some other examples are:
enum dayType { SUN, MON, TUE, WED, THU, FRI, SAT };
enum suitType { CLUBS, DIAMONDS, HEARTS, SPADES };
enum FaceCardValues { JACK = 11, QUEEN, KING, ACE};
-
There is a serious drawback in the use of enumerated types.
The values of an enumerated type variable can only be input and output as the integers that they represent.
Thus the statements:
dayType day;
day = WED;
cout << day;
produce the output 3, not WED.
And in response to the statements
cout << "Enter the day: ";
cin >> day;
the user must type an integer from 0 to 6, inclusive, not one of the symbolic names MON, TUE, etc.
If you must output the symbolic name of an enumerated type value,
you must translate the value into a string.
A string-values function such as the following is most useful for this purpose.
string Day2String(dayType day)
{
switch (day)
{
cast MON: return "Monday";
cast TUE: return "Tuesday";
cast WED: return "Wednesday";
cast THU: return "Thursday";
cast FRI: return "Friday";
cast SAT: return "Saturday";
cast SUN: return "Sunday";
}
}
Now, the fragment
dayType day;
day = WED;
cout << Day2String(day);
would produce the output Wednesday.