Enumeration Types
Enumeration types are used to define variables that can only be
assigned certain discrete integer values throughout the program. The
possible values and names for them are defined in an enumeration. The
type specifier begins with the keyword
enum
; for example:
enum toggle { OFF, ON, NO = 0, YES };
The list of enumerators inside the braces defines the new enumeration
type. The identifier toggle
is the
tag
of this
enumeration. This enumeration defines the identifiers in the list
(OFF
, ON
,
NO
, and YES
) as constants with
type int
.
The value of each identifier in the list may be determined
explicitly, as in NO = 0
in the example above.
Identifiers for which no explicit value is specified are assigned a
value automatically based on their position in the list, as follows:
An enumerator without an explicit value has the value
0
if it is the first in the list; otherwise its
value is 1 greater than that of the preceding enumerator. Thus in the
example above, the constants OFF
and
NO
have the value 0
, while
ON
and YES
have the value
1
.
Once an enumeration type has been defined, variables with the type can be declared within its scope. For example:
enum toggle t1, t2 = ON;
This declaration defines t1
and
t2
as variables with type enum
toggle
, and also initializes t2
with the
value ON
, or 1.
Following is an enumeration without a tag:
enum { black, blue, green, cyan, red, magenta, white };
As this example illustrates, the definition of an enumeration does not necessarily include ...
Get C Pocket Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.