Wednesday, March 24, 2010

Declaring Enumerations

We can declare the enumeration by using the enum keyword, as shown in the following example that enumerates the seasons of the year:
enum  Seasons{ Summer, Fall, Winter, Spring };
Each enumeration element (enumerator) has a value. The value of the first enumerator is 0 by default. The value of each successive element is incremented by 1. Thus the values of the elements in this enum are:
enum Seasons
{
    Summer,    //0
    Fall,        //1
    Winter,    //2
    Spring    //3
};
We can force the elements to start at 1 as in this example:
enum Seasons { Summer = 1, Fall, Winter, Spring };
In this enumeration, the values of the successive elements are indicated below:
enum Seasons
{
    Summer = 1,
    Fall,        //2
    Winter,     //3
    Spring    //4
};
We can assign a value to any element – not necessarily the first one:
enum WeekDays { Sat, Sun, Mon = 9, Thu, Wed, Thu, Fri };
This will make the values of the elements that follow Mon 10, 11, 12, and 13. However, Sat and Sun will still be 0 and 1.
We can also assign integers to the elements as appropriate. In this example, scores that correspond to grades are assigned:
enum Grades { Pass = 65, Good = 75, VeryGood = 85, Distinct = 100 };
We can choose another underlying type rather than int, such as long, if we need to use numbers in that range for the elements:
    enum Color: long {Red, Green, Blue};
The enumeration identifier is followed by a colon and then the underlying type.

No comments:

Post a Comment