< Previous | Contents | Next >

Using Enumerations

An enumeration is a set of unsigned int constants, called enumerators. Usually the enumerators are related and have a particular order. Heres an example of an enumeration:

enum difficulty {NOVICE, EASY, NORMAL, HARD, UNBEATABLE};

This defines an enumeration named difficulty. By default, the value of enumerators begins at zero and increases by one. So NOVICE is 0, EASY is 1, NORMAL is 2, HARD is 3, and UNBEATABLE is 4. To define an enumeration of your own, use the keyword enum followed by an identifier, followed by a list of enumerators between curly braces.

Next I create a variable of this new enumeration type.

difficulty myDifficulty = EASY;

The variable myDifficulty is set to EASY (which is equal to 1). myDifficulty is of type difficulty, so it can only hold one of the values defined in the enumeration. That means myDifficulty can only be assigned NOVICE, EASY, NORMAL, HARD, UNBEATABLE, 0, 1, 2, 3, or 4.

32 Chapter 1 n Types, Variables, and Standard I/O: Lost Fortune


Next I define another enumeration.

enum shipCost {FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50};

This line of code defines the enumeration shipCost, which represents the cost in Resource Points for three kinds of ships in a strategy game. In it, I assign specific integer values to some of the enumerators. The numbers represent the Resource Point value of each ship. You can assign values to the enumerators if you want. Any enumerators that are not assigned values get the value of the previous enumerator plus one. Because I didnt assign a value to BOMBER_COST, its initialized to 26.

Next I define a variable of this new enumeration type.

shipCost myShipCost = BOMBER_COST;

Then I demonstrate how you can use enumerators in arithmetic calculations.

(CRUISER_COST - myShipCost)

This piece of code calculates the cost of upgrading a Bomber to a Cruiser. The calculation is the same as 50 - 26, which evaluates to 24.