 |
Department of Engineering |
 |
 |
Enumeration and C++
Enumerated types are user-defined types whose variables can have a particular set of
integer values. They can be named, as in
enum WeekendDay {Saturday, Sunday};
(after which constants Saturday and Sunday can be used in place of 0
and 1, and variables of type WeekendDay can be created)
or unnamed, as in
enum {Sat, Sun};
after which the constants Sat and Sun can be used in place of 0
and 1. By default the values start at 0 and then increment by 1, but that can be overridden. For example, in
enum {Mon=3, Tue, Wed=2, Thu};
Mon is 3, Tue is 4, Wed is 2 and Thu is 3 (note that the values needn't be unique).
They can be used where integer-like values are required, so the following
works
int i=Sat;
but conversion doesn't work the other way - the following doesn't compile
WeekendDay w=1;
You need to do
WeekendDay w=static_cast<WeekendDay>(1);
Disadvantages
Though enumerations can make code more readable, they're
less useful for making code more robust.
- It's possible to variables of enumerated types to values outside
their allowed range. Compilers won't complain about the following
WeekendDay w=static_cast<WeekendDay>(99);
(though the result's undefined)
- Though you can't set an enumerated variable to an integer, you can set it to an unrelated enumerated value. The following isn't illegal
int main() {
enum WeekendDay {Saturday, Sunday};
enum Fruit {Apple, Orange, Pear};
WeekendDay w;
Fruit f=Pear;
w=Orange;
w=f;
}
- If you print such a variable, you'll get an integer, not a useful
string like Saturday