Skip to main content
Logo image

Section 32.2 Enumerated Types

Imagine you are programming a traffic light, and you decide that 0 means red, 1 means yellow, and 2 means green. Somewhere in your code you write if (light == 1) { ... }. Three months later, you (or a teammate) look at that line and have to ask: “wait, what did 1 mean again?” These bare numbers, with no obvious meaning attached, are sometimes called magic numbers, and they are a common source of bugs and confusion.
An enum (short for enumeration) solves this by letting us assign human-readable names to a set of related integer constants:
enum day { MON, TUE, WED, THU, FRI, SAT, SUN };
// MON == 0, SUN == 6
By default, the constants start at 0 and increase by 1, but under the hood the computer still just sees plain integers— an enum takes up the same amount of memory and runs exactly as fast as an int. It’s purely there for us, to make the code more readable. A variable of an enum type can be used just like any other integer variable:

admin.....open in new window

You can also assign specific values to some or all of the constants, rather than relying on the automatic 0, 1, 2, … numbering. This is especially handy when, for example, an enum needs to match status codes coming from an external sensor or device. Since such raw codes typically arrive as plain ints, we cast them into our enum type:

admin.....open in new window

Enums are perfect for anything with a limited, specific set of options: days of the week, months of the year, difficulty levels, or the states of a machine (like ON, OFF, STANDBY). They also pair naturally with switch statements, since each case can use a readable constant name instead of a bare number.

Activity 32.4.

We want to write code that helps us figure out whether it is currently summer. Declare an enum month with all twelve months (think about what value you want the first month to have). Ask the user to enter the number of the current month, and cast their integer input into your enum type. Finally, write a switch statement using your enum constants that prints “It’s the summer” during June, July, August, or September, and “It’s not summer” otherwise.

admin.....open in new window

Record your code below.

Activity 32.5.

Improve the “Machine State” example from above so that it prints the actual name of the state as text, rather than just printing the integer. To do this, add a function printStateName() that takes the machine state as an input parameter, and, inside the function, uses a switch statement to print the correct text for each case.

admin.....open in new window

Record your code below.