Author: Steve Norman
First published: 11 February 1997
Last modified: Tue Feb 11 10:43:41 MST 1997
The traditional C way of doing this was something like this:
An alternate approach using enum would be#define SPRING 0 #define SUMMER 1 #define FALL 2 #define WINTER 3
enum { SPRING, SUMMER, FALL, WINTER };
enum MyEnumType { ALPHA, BETA, GAMMA };
If you give an enum type a name, you can use that
type for variables, function arguments and return values, and so on:
The other kind creates an unnamed type. This is used when you want names for constants but don't plan to use the type to declare variables, function arguments, etc. For example, you can writeenum MyEnumType x; /* legal in both C and C++ */ MyEnumType y; // legal only in C++
enum { HOMER, MARGE, BART, LISA, MAGGIE };
enum MyEnumType { ALPHA, BETA, GAMMA };
ALPHA has a value of 0,
BETA has a value of 1,
and GAMMA has a value of 2.
If you want, you may provide explicit values for enum constants, as in
enum FooSize { SMALL = 10, MEDIUM = 100, LARGE = 1000 };
There is an implicit conversion from any enum type to int. Suppose this type exists:
enum MyEnumType { ALPHA, BETA, GAMMA };
Then the following lines are legal:
int i = BETA; // give i a value of 1 int j = 3 + GAMMA; // give j a value of 5
On the other hand, there is not an implicit conversion from int to an enum type:
Note that it doesn't matter whether the int matches one of the constants of the enum type; the type conversion is always illegal.MyEnumType x = 2; // should NOT be allowed by compiler MyEnumType y = 123; // should NOT be allowed by compiler