The “enumeration type” specifies a set of named integer constants, similar to the enumerated type in QuickPascal. In the C language, enumeration types are declared with the enum keyword.
Summary: Use enum to name a set of integer constants.
The enum type is useful mainly for improving a program's readability. With enum, you can use meaningful names for a set of constants whose purpose might not otherwise be apparent.
Suppose you're writing a calendar program in which the constant 0 represents Saturday, 1 represents Sunday, and so on. You might begin by declaring the enumeration type day in the following manner:
enum day
{
saturday, sunday, monday, tuesday,
wednesday, thursday, friday
};
Notice this declaration's similarity to a structure declaration. As with structures, the type declaration creates a template that you can use to declare variables of this type. (For more information, see “Declaring a Structure Type”.)
Unless you specify otherwise, the first value in an enumeration type equals 0 and others are numbered sequentially. In the enum type shown above, saturday equals 0, sunday equals 1, and so forth.
The values in an enumeration type need not be sequential, however. If you want some other order, you can declare explicit values for each member of the type. The following declaration, for example, assigns the names zero, freeze, and boil to the constants 0, 32, and 220, respectively.
enum temps
{
zero = 0,
freeze = 32,
boil = 220
};
After declaring an enumeration type, you can create a variable of that type and assign it a value from the type. The statement
enum day today = wednesday;
declares the variable today, assigning it the value wednesday from the day enumeration type.
After you assign its value, you can use the variable today as you would an int variable. Although the variable is considered to have the enum type, it is an ordinary int for all practical purposes.
Enumeration types aren't used very often, partly because you can achieve a similar effect using the #define directive. (For a detailed explanation of #define, see topic .) For example, the code
#define SATURDAY 0
#define SUNDAY 1
#define MONDAY 2
#define TUESDAY 3
#define WEDNESDAY 4
.
.
.
int today = WEDNESDAY;
uses #define to create symbolic constants named SATURDAY, SUNDAY, MONDAY, TUESDAY, and WEDNESDAY, assigning them the values 0 through 4. The last line in the example creates the int variable today and assigns it the value of WEDNESDAY. The result is identical to the statement shown earlier:
enum day today = wednesday;
One advantage of using enum over #define directives is that it groups related names in one place and can be more compact than a long series of directives.
This concludes our main discussion of data types. The next chapter, “Operators,” examines the C language's rich set of operators, which allow you to manipulate data in many different ways.