Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Enumeration Data Types: A Data Type Is

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 10

1

Enumeration Data Types


A data type is
A set of values together with A set of operations on those values.

In order to define a new simple data type, called enumeration type, we need: A name for the data type. A set of values for the data type. A set of operations on the values.

Enumeration Data Types


C++ allows the user to define a new simple data type by specifying:
Its name and the values

But not the operations.

The values that we specify for the data type must be legal identifiers The syntax for declaring an enumeration type is:
enum typeName{value1, value2, ...};

Declaration of Enumerated Types


Consider the colors of the rainbow as an enumerated type:
enum rainbowColors = { red, orange, yellow, green, blue, indigo, violate }

The identifiers between { } are called enumerators The order of the declaration is significant red < orange < yellow

Declaration of Enumerated Types


Why are the following illegal declarations?
enum grades{'A', 'B', 'C', 'D', 'F'}; enum places{1st, 2nd, 3rd, 4th};
They do not have legal identifiers in the list

What could you do to make them legal?


enum grades{A, B, C, D, F}; enum places{first, second, third, fourth};

Declaration of Enumerated Types


As with the declaration of any object
Specify the type name Followed by the objects of that type

Given:
enum daysOfWeek { Sun, Mon, Tue,Wed, Thu, Fri, Sat }

Then we declare:
daysOfWeek Today, payDay, dayOff;

Assignment with Enumerated Types


Once an enumerated variable has been declared
It may be assigned an enumerated value Assignment statement works as expected

payDay = Fri;

// note no quotes // Fri is a value, a constant

Enumerated variables may receive only values of that enumerated type

Operations on Enumerated Type Objects Incrementing variables of an enumerated type Do NOT use NOR workaday += 1; today++;

Instead, use explicit type conversion today = daysOfWeek (today + 1);

Operations on Enumerated Type Objects Comparison


normal, OK in order of the enumeration definition

I/O
generally not possible to do directly can be sort of done, indirectly

Used primarily for program control, branching, looping Possible to have functions return an enumerated type

Looping with Enumeration Types


Use an enumerated type variable as the loop control variable of a for loop
for (day = Mon; day < Sat; day = static_cast<daysOfWeek>(day + 1)) { . . . } This works because the values are represented internally as integers

13

The typedef statement


Syntax:
typedef existing_type_name new_type_name;

Example: typedef int Boolean;


Does not really create a new type
is a valuable tool for writing self-documenting

programs

You might also like