C++ Notes: Enum Values and I/O
Setting enum values
It's possible to control the values that are assigned to
each enum constant. If a value is assingned to a constant,
each successive constant without a value is assigned a value
one greater than the previous.
enum Day {MON=1, TUE, WED, THU, FRI, SAT, SUN};
The value of MON is one, TUE is two, etc instead of starting at zero.
Another use of specific values is to create sets.
Explicitly setting the values to powers of two represents each as separate bit.
These values can then manipulated using the bit operations (&, |, ^ and ~).
enum Day {MON=1, TUE=2, WED=4, THU=8, FRI=16, SAT=32, SUN=64};
const int WEEKDAY = MON+TUE+WED+THU+FRI;
. . .
Day today; // This will have one of the values in it.
. . .
if ((today & WEEKDAY) != 0) . . .
Enum I/O
I/O of enums uses their integer values, not their names.
This is not what is desired normally, so extra
programming is required on input and output to
use the names instead of integer values.
The extra work for enum I/O means that they
are often not used for simple programs.
Other languages
Java will have type-safe enums in version 1.5.
Currently it requires programmers to
explicitly declare each name as a constant ints.
C# provides enums with additional facilities, eg to get names and check values.
Related pages
Enum.