Upload
dina-walker
View
216
Download
0
Embed Size (px)
DESCRIPTION
Enumeration via constants One method to use enumerated type #defineSunday0 #defineMonday1 #defineTuesday2 #defineWednesday3 #defineThursday4 #defineFriday5 #defineSaturday6 Then can use if (day == Sunday) cout
Citation preview
CSci 162
Lecture 2
Martin van Bommel
Enumeration
• 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, ...
Enumeration via constants• One method to use enumerated type#define Sunday 0#define Monday 1#define Tuesday 2#define Wednesday 3#define Thursday 4#define Friday 5#define Saturday 6
• Then can useif (day == Sunday) cout << ”Rest today\n”;
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
Enumerated Type Definitionenum typename { list of elements};
• Exampleenum weekdayT { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
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 previousenum yearT{Freshman=1,Sophmore,Junior,Senior
};
Operations of Enumerated Types
• Values of enumerated type is implicitly converted to integer
• Integer not implicitly converted to enumweekdayT day = Monday;int d;d = (day + 1) % 7;day = (weekdayT) d;day = (weekdayT) ( (day + 1) % 7 );
Displaying value of type
• Use function to display value of typevoid PrintDay(weekdayT day){switch(day) { case Sunday: cout << ”Sunday”;break;
case Monday: cout << ”Monday”;break;etc.}
}
Another Way to Display Value
void PrintDay(weekdayT day){ string name[] = {”Sunday”,”Monday”,…}; cout << name[day];}
Characters
• Characters are internally defined almost like an enumerated type
enum char {…,’0’,’1’,…,’9’,’:’,’;’,…,’@’,’A’,’B’,
…,’Z’,’[’,…,’`’,’a’,…,’z’,…};
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”
Array Indexed by enum• Since values of enumerated type are
implicitly converted to integer, can use as indices to arrayint sales[7], i, total = 0;
sales[Monday] = 10000;
for (i=Sunday; i<=Saturday; i++) {total += sales[i];}