50 likes | 171 Views
Types. The type of a variable represents a set of values that may be assigned to the variable. For example, an integer variable is one that may take the values –2 31 to 2 31 – 1 What if we want a variable that may take values from a non-numerical set?
E N D
Types • The type of a variable represents a set of values that may be assigned to the variable. • For example, an integer variable is one that may take the values –231 to 231 – 1 • What if we want a variable that may take values from a non-numerical set? • For example, variable day may take values from the set {MON, TUE, WED, THU, FRI, SAT, SUN} • We could use integers to represent the days, but then the program would not be very readable • Which is best? today = 1 or today = MON ?
Enumerations • An enumerated type is a set of values defined by the programmer. • Each element of an enumerated type is given a unique name by the programmer. • Example: enum{MON, TUE, WED, THU, FRI, SAT, SUN} • Each element of an enumerated type is internally represented by an integer. • Unless the programmer explicitly specifies the integers, the values are consecutive starting at 0.
Enumerations • In order to be able to declare enumerated variables, an enumeration must be given a name. • Example: int main () { enum dayT {MON, TUE, WED, THU, FRI, SAT, SUN}; dayT today, tomorrow; today = MON; cout << today; // this will print 0 ... }
Enumerations • enum dayT {MON, TUE, WED, THU, FRI, SAT, SUN}; • MON, TUE, etc. are called “enumeration constants” • CAUTION! When you declare dayT today; , today is represented by an integer but not considered to be one. • Example: today = 3; is not allowed, even though THU is stored as a 3. 0 1 2 3 4 5 6
Enumerations • Since enumeration constants are represented by integers, if we print their values, we get an integer on the screen. In order to get a more meaningful name, we typically use an appropriate switch statement: switch(today) { case MON: cout << "Monday"; break; case TUE: cout << "Tuesday"; break; ... default: cout << "Unknown"; break; }