An enumerated type is used to restrict the possible values of an
object to 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 that 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.
An enumerated type is a set of scalar objects that have type names.
Variables are declared with enum specifiers in the place of the
type specifier. An enumerated type can have one of the following
forms:
enum { enumerator,... }
enum tag { enumerator,... }
enum tag
Each enumerator defines a constant of the enumerated type (tag).
The enumerator list forms an ordered list of the type's values.
Each enumerator has the form "identifier [= expression]", where the
"identifier" is the name to be used for the constant value and the
optional "expression" gives its integer equivalent. If a tag
appears but no list of enumerators, the enum-specifier refers to a
previous definition of the enumerated type, identified by the tag.
The following example declares an enumerated object
'background_color' with a list of enumeration constants:
enum colors { black, red, blue, green, } background_color;
Later in the program, a value can be assigned to the object
'background_color':
background_color = red;
In this example, the compiler automatically assigns the integer
values as follows: black = 0, red = 1, blue = 2, and green = 3.
Alternatively, explicit values can be assigned during the
enumerated type definition:
enum colors { black = 5, red = 10, blue, green = black+2 };
Here, black equals the integer value 5, red = 10, blue = 11, and
green = 7. 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.