Enumerated Data Types

The keyword enum (short for enumeration) allows you to create a new data type that consists of a set of named constants called the enumerator list. Each enumeration type has an underlying data type, which can be any integral type except char. The declaration of an enumerated data type takes the following form:

enum enum_name
} object_names;

In the example above, enum_name is the name given to the enumerated type, while object_names represents an optional list of objects of type enum_name. The enumerator list is enclosed within curly braces { }. The following declaration creates an enumerated data type called rgb_cols that stores the colours of the additive colour model.

enum rgb_cols {red, green, blue};

A variable having an enumerated data type may only take one of the constant values included in the enumerator list. The following code fragment shows how the rgb_cols enumerated type might be used:

rgb_cols mycolour;

mycolour = blue;
if (mycolour == green) mycolour = red;

Each constant value in the enumerator list of an enumerated data type is represented internally by an integer value. If not otherwise specified, the first value in the list is represented by 0, the second value is represented by 1, and so on. In the rgb_cols data type, therefore, red is equivalent to 0, green is equivalent to 1, and blue is equivalent to 2. You can, if you wish, specify the integer values that will represent the constant values in the enumerator list. If a specific integer value is not defined for any item in the list, it is automatically assigned an integer value that is one greater than the previous item in the list. In the following declaration, the constant values in the enumerator list are represented internally by integer values from 1 to 7:

enum weekdays {mon=1, tue, wed, thu, fri, sat, sun};