Enums
In C++, an enumeration (enum) is a user defined type where a set of values is specified for a variable and the variable can only take one out of a small set of possible values.
Syntax
The keyword enum
is used to define an enumeration.
enum name {const1, const2, ...};
Here’s an example:
enum day {sun, mon, tue, wed, thu, fri, sat};
sun
would have the value 0mon
would have the value 1tue
would have the value 2wed
would have the value 3thu
would have the value 4fri
would have the value 5sat
would have the value 6
Here’a another example where one of the constants is assigned a value:
enum grade {freshman=9, sophomore, junior, senior};
The enumerator freshman
is assigned the value 9
. Subsequent enumerators, if they are not given an explicit value, receive the value of the previous enumerator plus one.
So here:
freshman
would have the value 9sophomore
would have the value 10junior
would have the value 11senior
would have the value 12