Enum: Enumerations
Enumerations are used to define sets of integer values and for defining types for such sets of values. There are two kind of enumerations, "plain" enum
s and class enum
s.
Enumeration rule summary:
- Enum.1: Prefer enums over macros
- Enum.2: Use enumerations to represent sets of named constants
- Enum.3: Prefer class enums over "plain" enums
- Enum.4: Define operations on enumerations for safe and simple use
- Enum.5: Don't use
ALL_CAPS
for enumerators - Enum.6: Use unnamed enumerations for ???
- ???
Enum.1: Prefer enums over macros
Reason
Macros do not obey scope and type rules. Also, macro names are removed during preprocessing and so usually don't appear in tools like debuggers.
Example
First some bad old code:
// webcolors.h (third party header)
#define RED 0xFF0000
#define GREEN 0x00FF00
#define BLUE 0x0000FF
// productinfo.h
// The following define product subtypes based on color
#define RED 0
#define PURPLE 1
#define BLUE 2
int webby = BLUE; // webby == 2; probably not what was desired
Instead use an enum
:
enum class Webcolor { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
enum class Productinfo { red = 0, purple = 1, blue = 2 };
int webby = blue; // error: be specific
Webcolor webby = Webcolor::blue;
Enforcement
Flag macros that define integer values
Enum.2: Use enumerations to represent sets of named constants
Reason
An enumeration shows the enumerators to be related and can be a named type
Example
enum class Webcolor { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
Enforcement
???
Enum.3: Prefer class enums over "plain" enums
Reason
To minimize surprises: traditional enums convert to int too readily.
Example
void PrintColor(int color);
enum Webcolor { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
enum Productinfo { Red=0, Purple=1, Blue=2 };
Webcolor webby = Webcolor::blue;
// Clearly at least one of these calls is buggy.
PrintColor(webby);
PrintColor(Productinfo::Blue);
Instead use an enum class
:
void PrintColor(int color);
enum class Webcolor { red=0xFF0000, green=0x00FF00, blue=0x0000FF };
enum class Productinfo { red=0, purple=1, blue=2 };
Webcolor webby = Webcolor::blue;
PrintColor(webby); // Error: cannot convert Webcolor to int.
PrintColor(Productinfo::Red); // Error: cannot convert Productinfo to int.
Enforcement
(Simple) Warn on any non-class enum definition.
Enum.4: Define operations on enumerations for safe and simple use
Reason
Convenience of use and avoidance of errors.
Example
???
Enforcement
???
Enum.5: Don't use ALL_CAPS
for enumerators
Reason
Avoid clashes with macros.
Example
???
Enforcement
???
Enum.6: Use unnamed enumerations for ???
Reason
???
Example
???
Enforcement
???