Previous Page
Next Page

2.5. Enumerated Types

Enumerations are integer types that you define in a program. The definition of an enumeration begins with the keyword enum, possibly followed by an identifier for the enumeration, and contains a list of the type's possible values, with a name for each value:

    enum [identifier] { enumerator-list };

The following example defines the enumerated type enum color:

    enum color { black, red, green, yellow, blue, white=7, gray };

The identifier color is the tag of this enumeration. The identifiers in the listblack, red, and so onare the enumeration constants , and have the type int. You can use these constants anywhere within their scopeas case constants in a switch statement, for example.

Each enumeration constant of a given enumerated type represents a certain value, which is determined either implicitly by its position in the list, or explicitly by initialization with a constant expression. A constant without an initialization has the value 0 if it is the first constant in the list, or the value of the preceding constant plus one. Thus in the previous example, the constants listed have the values 0, 1, 2, 3, 4, 7, 8.

Within an enumerated type's scope, you can use the type in declarations:

    enum color bgColor = blue,         // Define two variables
               fgColor = yellow;       // of type enum color.
    void setFgColor( enum color fgc ); // Declare a function with a parameter
                                       // of type enum color.

An enumerated type always corresponds to one of the standard integer types. Thus your C programs may perform ordinary arithmetic operations with variables of enumerated types. The compiler may select the appropriate integer type depending on the defined values of the enumeration constants. In the previous example, the type char would be sufficient to represent all the values of the enumerated type enum color.

Different constants in an enumeration may have the same value:

    enum { OFF, ON, STOP = 0, GO = 1, CLOSED = 0, OPEN = 1 };

As the preceding example also illustrates, the definition of an enumerated type does not necessarily have to include a tag. Omitting the tag makes sense if you want only to define constants, and not declare any variables of the given type. Defining integer constants in this way is generally preferable to using a long list of #define directives, as the enumeration provides the compiler with the names of the constants as well as their numeric values. These names are a great advantage in a debugger's display, for example.

Previous Page
Next Page