Enum Variables

Enumeration (enum): An enum is a user-defined type consisting of a set of named constants called enumerators. 
For e.g.the colors of the rainbow would be mapped like this 

         enum rainbowcolors

Now internally, the compiler will use an int to hold these and if no values are supplied, red will be 0, orange is 1 etc. It maintains a table containing data, mapped with an integer associated with it.

Enumerators are stored by compiler as an integers: by default, first enumerator is 0, next enumerator value is previous enumerator value + 1.

You aren't stuck with these compilers generated values; you can assign your own integer constant to them as shown here.

         enum rainbowcolors
                       Blue =8, 
                       Indigo =8, 
                       Violet =16
         } ; 

Having blue and indigo with the same value isn't a mistake as enumerators might include synonyms such as scarlet and crimson.

Enum Declaration:           
 In C, the variable declaration must be preceded by the word enum as in 
                     enum rainbowcolors trafficlights= red; 

C++ has enumeration types that are directly inherited from C's and work mostly like these, except that an enumeration is a real type in C++, giving additional compile-time checking. Also (as with structs) the C++ "enum" keyword is automatically combined with a "typedef", so that instead of calling the type "enum name", one simply calls it "name."
This can be simulated in C using a typedef: "typedef enum {TYPE1, TYPE2} name;"


  • They restrict the values that the enum variable can take. 
  • They force you to think about all the possible values that the enum can take. 
  • They are a constant rather than a number, increasing readability of the sourcecode. 

No comments:

Post a Comment