Enumerations
 

User-defined types:

Here are three common ways of defining your own types:
  1. class
  2. typedef
  3. enum (enumeration)

Enumerations: This page focuses on the enumeration. When you create an enumerated type, you are making up a new type that has a small set of specific values, which are listed in the declaration. The compiler will implement these as a set of constants. To create an enumeration, use the keyword enum, and the following syntax:

  enum Names {RALPH, JOE, FRED}; 

Now, if you declare a variable of type Names, the symbols RALPH, JOE, and FRED are the actual values that can be used with these variables.  Note, these words are NOT character strings.  They are stored by the computer as constant values.  Enumerations are essentially used for making code easier to read, and the values of certain variables easier to remember.  Examples of uses of this enum declared above:

  Names who;    // who is a variable of type Names 

  who = FRED;        // assign the value FRED to the variable who 
  if (who == JOE) 
      cout << "Halleluia!"; 
  who = JOE; 
  switch(who) 
  {   case JOE:    cout << "Joe"; break; 
      case FRED:   cout << "Fred"; break; 
      case RALPH:  cout << "Ralph"; break; 
  } 

Another enumeration example:

  enum Days {SUN, MON, TUE, WED, THUR, FRI, SAT}; 

  Days today, tomorrow, yesterday; 

  today = MON; 
  if (today == SUN) 
      yesterday = SAT; 
  if (tomorrow == FRI) 
      cout << "Today is Thursday!"); 

Important advantages of enumerations