Home   Cover Cover Cover Cover
 

Enumerations

Question: What are the advantages of an enumeration type (e.g. enum Color {red, blue, green}) versus named int constants (e.g. const int red = 0, blue = 1, green = 2;)?

Answer: Enumerations have several advantages:

  • If enumeration constants are used instead of named int constants the compiler can perform more accurate type checks. If a variable has an enumeration type the compiler can guarantee that only values of this enumeration type are assigned to the variable. However, if the variable is of type int one can assign arbitrary numbers to it.


  • Since enumeration constants have to be qualified with the name of the corresponding enumeration type one can immediately see to which type these values belong. Besides, the explicit qualification avoids name clashes with identical names in other enumeration types.

On the other hand, named int constants are shorter to write (e.g. just red instead of Color.red). They can also be declared local to methods, which is not possible for enumeration constants.