TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
 
C++ Coding Standard
Search

Rule:  PCA#002Checked automatically with code checker

Synopsis:Do not assume that an enumerator has a specific value
Language:C++
Severity Level:4
Category:Parts of C++ to Avoid


Description:

A common pitfall is that it is assumed that the enumerators of an enumeration run from 0 to (max - 1). Although each enumerator has an integer value, no code may be written that relies on the integer value of the enumerator.

Incorrect example:

enum Color { red, green, blue };
Color color = 2;

Correct example:

enum Color { red, green, blue };
Color color = green;

Another mistake is to rely on the order of the enum elements. The order might change over time.

Incorrect example:

enum Color { red, green, blue };
if (color >= green) { ... }

Correct example:

enum Color { red, green, blue };
if (color == green || color == blue) { ... }

Important note. Instead of using old style enums, it is better to use enum classes. See also [PCA#016]. Enum classes don't allow conversions between enum values and integers. The compiler will issue a compiler error for this.