Programming C++  «Prev  Next»
Lesson 10Declarations and enumerated types
ObjectiveInitializing enumerated lists

Initializing enumerated lists in C++

Examine how to initialize an enumerated list.

In C, enumerated types are implemented as a form of int. C++ treats enumerated types as distinct types promotable to an int in expressions. When listed without initialized values, the identifiers in an enumerated list are implicitly initialized consecutively, starting with 0. These identifiers are named integer constants and cannot be changed.

So the declarations:
enum suit { clubs, diamonds, hearts, spades };
enum suit { clubs = 0, diamonds = 1, hearts = 2, spades = 3 };

are equivalent, as are:
enum suit { clubs = 5, diamonds, hearts,  spades = 3 };
enum suit { clubs = 5, diamonds = 6, hearts = 7, spades = 3 };


Enumerated Types

Sometimes a variable should only take values from a limited set of possibilities. For example, a variable describing a weekday (Monday, Tuesday, Wednesday, ... , Sunday) can have one of seven states. In C++, we can define such enumerated types:
enum Weekday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY, SUNDAY };

This makes Weekday a type, similar to int. As with any type, we can declare variables of that type.
Weekday homework_due_day = WEDNESDAY;

// Homework due every Wednesday Of course, you could have declared homework_due_day as an integer. Then you would need to encode the weekdays into numbers.
int homework_due_day = 2;

You could go on and define constants
const int MONDAY = 0;
const int TUESDAY = 1;
const int WEDNESDAY = 2;
const int THURSDAY = 3;
const int FRIDAY = 4;
const int SATURDAY = 5;
const int SUNDAY = 6;

However, the Weekday enumerated type is clearer, and it is a convenience that you need not come up with the integer values yourself. It also allows the compiler to catch programming errors. For example, the following is a compile-time error:

Weekday homework_due_day = 10; // Compile-time error

In contrast, the following statement will compile without complaint and create a logical problem when the program runs:
int homework_due_day = 10; // Logic error

It is a good idea to use an enumerated type whenever a variable can have a finite set of values.