17 Enum
17 Enum
4/10/2013
Ease of programming .
For example it might be more meaningful to use variables of type color whose values are one in {red, blue, green} color j; /* j is of type color */ j = blue; /* j is assigned with value blue */ if(j == red) { .; } So, how to create a simple user defined type like this?
2
4/10/2013
Enumeration constants
C provides a simple user defined type called enumeration. An enumeration, introduced by the keyword enum, is a set of integer constants represented by identifiers. These enumeration constants are, in effect, symbolic constants whose values can be set automatically.
4/10/2013
An example
enum day { sun, mon, tue, wed, thu, fri, sat }; This creates a new type, enum day enum day j; /* j can have a value from the prespecified set */ j = mon; /* OK */
4/10/2013
enum day { sun, mon, tue, wed, thu, fri, sat }; Actually, each identifier is assigned a integer code. In the above example, sun is a identifier whose code is 0, for mon the code is 1, ., for sat the code is 6. So, actually, when we say enum day j = mon; j is an integer variable and its value is 1. We can also specify the codes explicitly. Eg: enum color { red = 1, blue = 10, green = 100};
4/10/2013
Continuation
If the code values are not explicitly specified, then the code for the first identifier is 0, second identifier is 1, . If some identifiers are specified explicitly, then the remaining unspecified values continue the progression from the last specified value. enum color {red =5, blue, green}; red has code 5, blue has code 6, and green has code 7. More than one identifier can have the same code. enum escapes {BELL = \a, BACKSPACE = \b, TAB = \t};
4/10/2013
Enumeration is a betterment over #define #define red 0 #define blue 1 #define green 2 The above has almost the same effect as enum day {red, blue, green}; Nevertheless, it is a good programming practice to use appropriate enums; it improves readability.
7
4/10/2013