Clarifying programs with enum
An enumerated data type is a way of
attaching names to numbers, thereby giving more meaning to anyone reading the
code. The enum keyword
(from C) automatically enumerates any list of identifiers you give it by
assigning them values of 0, 1, 2, etc. You can declare enum variables
(which are always represented as integral values). The declaration of an
enum looks similar to a struct declaration.
An enumerated data type is useful when
you want to keep track of some sort of feature:
//: C03:Enum.cpp
// Keeping track of shapes
enum ShapeType {
circle,
square,
rectangle
}; // Must end with a semicolon like a struct
int main() {
ShapeType shape = circle;
// Activities here....
// Now do something based on what the shape is:
switch(shape) {
case circle: /* circle stuff */ break;
case square: /* square stuff */ break;
case rectangle: /* rectangle stuff */ break;
}
} ///:~
shape is a variable of the
ShapeType enumerated data type, and its value is compared with the value
in the enumeration. Since shape is really just an int, however, it
can be any value an int can hold (including a negative number). You can
also compare an int variable with a value in the
enumeration.
You should be aware that the example
above of switching on type turns out to be a problematic way to program. C++ has
a much better way to code this sort of thing, the explanation of which must be
delayed until much later in the book.
If you don’t like the way the
compiler assigns values, you can do it yourself, like this:
enum ShapeType {
circle = 10, square = 20, rectangle = 50
};
If you give values to some names and not
to others, the compiler will use the next integral value. For
example,
enum snap { crackle = 25, pop };
The compiler gives pop the value
26.
You can see how much more readable the
code is when you use enumerated data types. However, to some degree this is
still an attempt (in C) to accomplish the things that we can do with a
class in C++, so you’ll see enum used less in
C++.