Enumerations let us group together sets of integral constants. Like classes, each enumeration defines a new type. Enumerations are literal types (§ 7.5.6, p. 299).
C++ has two kinds of enumerations: scoped and unscoped. The new standard introduced scoped enumerations. We define a scoped enumeration using the keywords enum class
(or, equivalently, enum struct
), followed by the enumeration name and a comma-separated list of enumerators enclosed in curly braces. A semicolon follows the close curly:
enum class open_modes {input, output, append};
Here we defined an enumeration type named open_modes
that has three enumerators: input
, output
, and append
.
We define an unscoped enumeration by omitting the class
(or struct
) keyword. The enumeration name is optional in an unscoped enum
:
enum color {red, yellow, green}; // unscoped enumeration
// unnamed, unscoped enum
enum {floatPrec = 6, doublePrec = 10, double_doublePrec = 10};
If the enum
is unnamed, we may define objects of that type only as part of the enum
definition. As with a class definition, we can provide a comma-separated list of declarators between the close curly and the semicolon that ends the enum
definition (§ 2.6.1, p. 73).