Presentation is loading. Please wait.

Presentation is loading. Please wait.

Enumeration Types and typedef

Similar presentations


Presentation on theme: "Enumeration Types and typedef"— Presentation transcript:

1 Enumeration Types and typedef

2 enum Used to declare enumeration types.
Allows to name a finite set and to declare identifiers, called enumerators.

3 Creates the user-defined type enum day. tag name
constants of type int enum day {sun, mon, tue, wed, thu, fri, sat}; enum day d1, d2; d1 = fri; if (d1 == d2) 1 6

4 Enumerators can be initialized.
We can declare variables directly after the enumerator declaration. enum suit {clubs = 1, diamonds, hearts, spades} a, b, c; 2 3 4 enum fruit {apple = 7, pear, orange = 3, lemon} frt; 8 4

5 It is allowed, but the identifiers must be unique.
enum veg {beet = 17, corn = 17} vege1, vege2; It is allowed, but the identifiers must be unique. enum {fir, pine} tree; The tag name need not be present. But no other variables of type enum {fir, pine} can be declared.

6 typedef An identifier can be associated with a specific type.
typedef int color; color red, blue, green; The typedef facility allows the programmer to use type names that are appropriate for a specific application. Also, helps to control complexity when programmers are building complicated or lengthy user-defined types.

7 Example – Compute the next day
enum day {sun, mon, tue, wed, thu, fri, sat}; typedef enum day day; day find_next_day(day d) { day next_day; switch (d) { case sun: next_day = mon; break; tag name type

8 case mon: next_day = tue; break; case sat: next_day = sun; } return next_day;

9 Another Version cast enum day {sun, mon, tue, wed, thu, fri, sat};
typedef enum day day; day find_next_day(day d) { return((day) (((int) d + 1)%7)); } cast

10 Style Enumerators can be mnemonic. => Their use tends to be self-documenting. The use of enumeration types is considered good programming style. enum bool {false, true}; enum off_on {off, on}; enum no_yes {no, yes} enum speed {slow, fast} Put such declarations in header files. (good programming style)

11 Style All acceptable. Which one is used is a matter of personal taste.
enum lo_hi {lo, hi}; typedef enum lo_hi lo_hi; All acceptable. Which one is used is a matter of personal taste. typedef enum lo_hi {lo, hi} lo_hi; typedef enum {lo, hi} lo_hi;


Download ppt "Enumeration Types and typedef"

Similar presentations


Ads by Google