Thursday, October 15, 2009

12.4 enum Type




I l@ve RuBoard










12.4 enum Type



The enumerated
(enum) data type is designed for variables that
can contain only a limited set of values. These values are referenced
by name (tag[1]). The compiler assigns each tag an integer
value internally, such as the days of the week. You could use the
directive const
to create values for the days of the
week (day_of_the_week) as follows:


[1] Tags are also called
"named constants" or
"enumerators."



typedef int day_of_the_week;   // Define the type for days of the week

const int SUNDAY = 0;
const int MONDAY = 1;
const int TUESDAY = 2;
const int WEDNESDAY = 3;
const int THURSDAY = 4;
const int FRIDAY = 5;
const int SATURDAY = 6;

/* Now to use it */
day_of_the_week today = TUESDAY;


This method is cumbersome. A better method is to use the
enum type:



enum day_of_the_week {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,  
FRIDAY, SATURDAY};

/* Now use it */
enum day_of_the_week today = TUESDAY;


The general form of an enum statement is:



enum enum-name {tag-1, tag-2, . . .} variable-name;


As with structures, the enum-name or the
variable-name may be omitted. The tags may be
any valid C++ identifier; however, tags are usually all uppercase.



An additional advantage of using an enum type is
that C++ will restrict the values that can be used to the ones listed
in the enum declaration. Thus, the following will
result in a compiler error:



today = 5;  // 5 is not a day_of_the_week


If we want to force the issue, we have to use a
static_cast to transform 5 into a day:



today = static_cast<enum day_of_the_week>(5);


So far we've let C++ do the mapping from
enum tags to integers. For example, our
enum declaration:



enum day_of_the_week {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,  
FRIDAY, SATURDAY};


results in SUNDAY being assigned 0,
MONDAY gets 1, and so on. This works great if we
don't care about the mapping. But suppose we are
interfacing to a device that returns a set of error codes. We would
like to define an enum to hold them. The problem
is that the device returns error numbers and we need to map them
precisely to our enum tags. C++ lets you specify
the mapping values in your enum declaration:



enum ERROR_RETURNS {
MOTOR_FAILURE = 55,
POSITION_ERROR = 58,
OIL_FAILURE = 33
};








    I l@ve RuBoard



    No comments:

    Post a Comment