Enumeration is basically a way to represent a possible list of number values for a variable in friendly names or symbol forms. For e.g. if you have to represent rainbow colours with 0 to 6 you can always write them more meaningfully as
enum rainbow { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET };
This will essentially give values from 0 to 6 to given colours in that order. so if following code is written –
enum rainbow { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET };
rainbow colour;
colour = YELLOW;
cout<<colour;
Then output would be 2 as YELLOW is the third variable and its value would be integer 2 automatically.
Observation while using enumerated data types:
Please make following observations in the above declaration and usage in code.
- The declaration begins with prefix enum with a user defined data type name which in this case is rainbow.
- The declaration contains friendly value names separated by comma in a structure or class like declaration with curly braces and following semicolon.
- When used it follows a simple syntax of datatype name followed by a variable name which in this case is rainbow colour;
- The assigned variable can now be assigned only a value from within the given value list range only. If any thing else is assigned to variable name then compiler error will return. For e,g.
colour = YELLOW; is correct
colour=MAROON; is not correct as it is not there in the symbol list defined.
colour=2; will also not be correct as it may be internally assigned value but not present as a symbol in the given symbol list.
- Internally the symbol names in the list gets converted to values and when printed they print the value only.
- Enumeration may allow user given fixed values like –
enum rainbow { RED=1, ORANGE=2, YELLOW=3, GREEN=4, BLUE=5, INDIGO=6, VIOLET=7 };
Advantages of Enumeration:
- Allows to check for fixed set of values only for any variable.
- Allows to provide friendly names to list of values.
- The default values for value list is generated automatically from 0 to further as per number of items in the list. (This is converse to #define where providing values is a must)
- Is a good technique to assign multiple value combination as OR or AND form to the same variable.
- Additional value settings can be provided to a variable easily.
Watch Few Examples Here
Some Examples of Enumerated Data Types
- enum season{spring, summer,autumn,winter};
- enum gender{male,female,other};
- enum weekdays{monday,tuesday,wednesday,thursday,friday,sunday};
- enum cards{club,diamond,heart,spade};
- enum artist_primary_colours{RED, YELLLOW, BLUE};
- enum direction{east,west,north,south};
- enum error{Memory_Err,File_err,Hardware_Err,Communication_Err};
- enum session{morning,evening};
- enum boolean{false,true};
- enum attribs{bold,underline,italic};
- enum G7{Canada,France,Germany,Italy,Japan,UK,USA,EU};