1 / 5

Types

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?

lavada
Télécharger la présentation

Types

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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 ?

  2. 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.

  3. 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 ... }

  4. 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

  5. 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; }

More Related