Enumeration
Similar to structure, enumeration declaration can be
- Enumeration names form a separate namespace
enum ENUM {
member1 [= integer],
member2 [= integer]
};
usage in declarations and definitions requires keyword
enum
in C (recommended to C++ too)
enum ENUM e;
typedef
can be used to shorten
declarations and definitions
typedef enum ENUM Enum;
Enum e;
typedef
and enum
declarations can be combined into one construct
typedef enum ENUM {
member1 [= integer],
member2 [= integer]
} Enum;
- Typically, inner
enum
declaration
needs no name
typedef enum {
member1 [= integer],
member2 [= integer]
} Enum;
- In C++,
typedef
is optional.
enum Enum {
member1 [= integer],
member2 [= integer]
};
Enum e;
In C, the type of an enumerator is int. In C++, the type of an
enumerator is its enumeration. C++ objects of enumeration type can
only be assigned values of the same enumeration type.
enum Color {
Red,
Blue,
Green
} c = 1; // valid C, invalid C++
When necessary, however, an enumeration type is automatically
promoted to an arithmetic type. For example
Enum e = member1;
const int array_size = 1024;
int chunk_size = array_size * e; // promoted to int
In C++, iterate over the values using the enumerators is not allowed,
as there is no support for moving backward or forward from one
enumerator value to a succeeding or preceding one.
for (Enum e=member1; e!=member2; e++) // not supported
// ...
To print the actual enumerator names, define an array of strings
indexed by the value of the enumerator.
const char *EnumName[] = { "member1", "member2" };
Enum e = member1;
cout << EnumName[e] << endl;
e = member2;
cout << EnumName[e] << endl;
Index