Search Contact information
University of Cambridge Home Department of Engineering
University of Cambridge >  Engineering Department >  computing help >  Languages >  C++

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.
© Cambridge University Engineering Dept
Information provided by Tim Love (tpl)
Last updated: November 2008