2011-06-07

Enums in C++

"Should I use enumeration in this code, or could I just use plain integer/boolean type for representing set of unique integers?"

Enumerations are OK if:
  • you use the names in 'switch' statements
  • using values in template parameter and specializing on that parameter
  • semantics of some code will be changed if new value has been added
  • semantics of the code should not be changed if values of two variables in the set have been swapped
You'd better stick with plain integers if:
  • you routinely iterate through the values in 'for' loop
  • you perform arithmetics on the values
  • semantics of the code is not changed if new value has been added
  •  
    For values that represent strict binary choice -- yes/no, forward/backward, good/bad -- it is almost always great idea to have an enumeration instead of boolean type: it communicates an idea of variable semantics much cleaner.

    To sum up, you should use enumerations only if you are interested in the names, and not interested in the values (with an exception for serialization maybe), and if the set of integers is bound.

    No comments:

    Post a Comment