
Using Enumerations
and Structures
The data types you’ve learned about so far hold strings, integers, dates, and other pre-
defined kinds of information, but sometimes it would be nice to define your own data
types. Enumerations let you define a data type that can hold only certain values. For
example, a menu program might define a
MealType data type that can hold the values
Breakfast, Lunch, and Dinner.
The data types described in previous lessons also can hold only a single piece of data: a name,
address, date, or whatever. Sometimes it would be nice to keep related pieces of data together.
Instead of storing a name, address, and phone number in separate strings, you might like to
store them as a single unit.
Enumerations and structures let you do these things. An enumeration (or enumerated type) lets
you define a new data type that can take only one of an allowed list of values. A structure lets you
define a group of related pieces of data that should be kept together.
In this lesson, you learn how to define and use enumerations and structures to make your code
easier to understand and debug.
ENUMERATIONS
An enumeration is simply a data type that allows only specific values. The following code defines
a
ContactMethod enumeration that can hold the values None, Email, Phone, or SnailMail:
// Define possible contact methods.
enum ContactMethod
{
None = 0,
Email,
Phone,
SnailMail,
}
17
596906c17.indd ...