[CWC logo] C Keywords - enum


enum

Enumeration Types

In C you can define a list of named integer constants called an enumeration. These constants can then be used any place an integer can. To define an enumeration, use the general form:

enum tag-name {enumeration list} variable-list;

Either the tag-name or the variable-list is optional. The tag-name is essentially the type name of the enumeration. Enumeration variables may only contain values that are defined in the enumeration. For example, in the statement:

enum colour_type {red, green, yellow} colour;

the variable colour may be assigned only the values red, green or yellow.

By default, the compiler assigns integer values to the constants beginning with 0 at the far left side of the list. Each constant to the right is one greater than the constant that precedes it. Therefore in the colour enumeration, red is 0, green is 1 and yellow is 2. However you can override the compiler's default values by explicitly giving a constant value. For example:

enum colour-type {red, green=9, yellow} colour;

Once you have defined an enumeration, you can use its tag-name to declare enumeration variables at other points in your program. For example:

enum colour_type mycolour;

The main purposes of an enumeration are to help provide self-documenting code and to clarify the structure of your program. The enumeration types are declared at the head before main function. Some languages have boolean data types which can have the value true or false. Within C you can devise your own boolean data type using enumeration.


[Leicester University] [] Computer Centre
Information Suppliers: Richard Mobbs, Head of Information Services, Leicester University Computer Centre and Marina Carter, Postgraduate Student, Leicester University Computer Centre.
Last Updated: August 1995