An enumerated type is a user-defined integer type. An enumerated type defines enumeration constants, which are integral constant expressions with values that can be represented as integers. An enumerated type declaration follows this syntax:
enum identifier(opt) { enumerator-list} enum identifier
enumerator enumerator-list, enumerator
enumeration-constant enumeration-constant = constant_expression
In DEC C, objects of type enum
are
compatible with objects of type signed int
.
The following example shows the declaration of an enumeration type and an enumeration tag:
enum shades { off, verydim, dim, prettybright, bright } light;
This declaration defines the variable light
to be of an
enumerated type shades
. light
can assume
any of the enumerated values.
The tag shades
is the enumeration tag of the new type.
off
through bright
are the enumeration
constants with values 0 through 4. These enumeration constants
are constant values and can be used wherever integer constants are
valid.
Once a tag is declared, it can be used as a reference to that
enumerated type, as in the following declaration, where the variable
light1
is an object of the enumerated data type
shades
:
enum shades light1;
An incomplete type declaration of an enumerated type is illegal; for example:
enum e;
An enum
tag can have the same spelling as other
identifiers in the same program in other name spaces. However,
enum
constant names share the same name space as
variables and functions, so they must have unique names to avoid
ambiguity.
Internally, each enumeration constant is associated with an integer constant; the compiler gives the first enumeration constant the value 0 by default, and the remaining enumeration constants are incremented by 1 for each succeeding value. Any enumeration constant can be set to a specific integer constant value. The enumeration constants following such a construct (unless they are also set to specific values) then receive values that are one greater than the previous value. Consider the following example:
enum spectrum { red, yellow = 4, green, blue, indigo, violet } color2 = yellow;
This declaration gives red
, yellow
,
green
, blue
, . . . , the values 0, 4,
5, 6, . . . Assigning duplicate values to enumeration constants is
permitted.
The value of color2
is an integer (4), not a string
such as "red" or "yellow".