Download presentation
Presentation is loading. Please wait.
Published byDina Walker Modified over 9 years ago
1
CSci 162 Lecture 2 Martin van Bommel
2
Enumeration –process of listing all of the elements in the domain of a type Enumerated type –type defined via enumeration Representation of enumerated type –give each element a number e.g. 0, 1, 2, 3,...
3
Enumeration via constants One method to use enumerated type #defineSunday0 #defineMonday1 #defineTuesday2 #defineWednesday3 #defineThursday4 #defineFriday5 #defineSaturday6 Then can use if (day == Sunday) cout << ”Rest today\n”;
4
Defining Enumerated Types Better to use explicit type definition Why? –Compiler chooses integer codes –Programs easier to read with separate, meaningful type name –Easier to debug the program
5
Enumerated Type Definition enum typename { list of elements }; Example enum weekdayT { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
6
Enumerated types Values corresponding to elements of types are by default assigned sequentially from zero Can change this behavior: enum yearT { Freshman = 1, Sophmore = 2, Junior = 3, Senior = 4 }; Values assigned sequentially from previous enum yearT{ Freshman=1,Sophmore,Junior,Senior };
7
Operations of Enumerated Types Values of enumerated type is implicitly converted to integer Integer not implicitly converted to enum weekdayT day = Monday; int d; d = (day + 1) % 7; day = (weekdayT) d; day = (weekdayT) ( (day + 1) % 7 );
8
Displaying value of type Use function to display value of type void PrintDay(weekdayT day) { switch(day) { case Sunday: cout << ”Sunday”;break; case Monday: cout << ”Monday”;break; etc. }
9
Another Way to Display Value void PrintDay(weekdayT day) { string name[] = {”Sunday”,”Monday”,…}; cout << name[day]; }
10
Characters Characters are internally defined almost like an enumerated type enum char { …,’0’,’1’,…,’9’,’:’,’;’,…,’@’,’A’,’B’, …,’Z’,’[’,…,’`’,’a’,…,’z’,… };
11
Boolean Values The bool type is an enumerated type enum bool {false, true}; Functions with return type “bool” can return “false” or “true” and still be used in “if”
12
Array Indexed by enum Since values of enumerated type are implicitly converted to integer, can use as indices to array int sales[7], i, total = 0; sales[Monday] = 10000; for (i=Sunday; i<=Saturday; i++) { total += sales[i]; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.