3.6 Enumerated Types

An enumerated type is used to specify the possible values of an object from a predefined list. Elements of the list are called enumeration constants. The main use of enumerated types is to explicitly show the symbolic names, and therefore the intended purpose, of objects whose values can be represented with integer values.

Objects of enumerated type are interpreted as objects of type signed int , and are compatible with objects of other integral types.

The compiler automatically assigns integer values to each of the enumeration constants, beginning with 0. The following example declares an enumerated object background_color with a list of enumeration constants:

enum colors { black, red, blue, green, white } background_color;

Later in the program, a value can be assigned to the object background_color :

background_color = white;

In this example, the compiler automatically assigns the integer values as follows: black = 0, red = 1, blue = 2, green = 3, and white = 4. Alternatively, explicit values can be assigned during the enumerated type definition:

enum colors { black = 5, red = 10, blue, green = 7, white = green+2 };

Here, black equals the integer value 5, red = 10, blue = 11, green = 7, and white = 9. Note that blue equals the value of the previous constant (red ) plus one, and green is allowed to be out of sequential order.

Because the ANSI C standard is not strict about assignment to enumerated types, any assigned value not in the predefined list is accepted without complaint.


Previous Page | Next Page | Table of Contents | Index