parts/6.05.EnumeratorIssues-CCB.md

6.5 Enumerator Issues [CCB]

6.5.1 Applicability to language

The vulnerability documented in ISO IEC 24772-1 clause 6.5 applies to C++. C++ provides scoped (enum class) and unscoped (enum) enumeration types, where an underlying integral type can be specified. For enumeration types with a fixed underlying type all values of the underlying integral type are valid. Unscoped enumeration types without an enum-base have a non-fixed underlying type that only guarantees values in the range of the provided enumerators are valid. The latter can cause non-representable values to be assigned to a variable of such an unscoped enumeration type.

Assignment of a variable of an enum type require the assigned value to be of the same enum type. This can be either an enumerator of that enum type, or requires a cast (see 6.6 Conversion errors [FLC]).

C++ allows implicit conversion of an unscoped enum by integral promotion.

TODO continue here

enum Color  {red, green, blue};
short i = red; // implicit conversion
Color g { green + blue }; // integer result fits into short
Color h {42}; // OK non-narrowing

List initialization of enum types with fixed underlying type implicitly does a static cast.

C++ does not support implicit conversion of a scoped enum to an int, hence, operations such as ++, +, < and enums used as array indices require explicit definitions.

enum class Color : short {red, green, blue};
short i = red; // error -- no implicit conversion

Where unscoped enums are used as array indexes and do not have a user-specified mapping to an underlying representation, there will be “holes” as documented in TR24772-1 clause 6.6.

Note that unscoped enumeration types implicitly promote their underlying type and can be used as the index of an array without a cast, with all of the issues described in TR 24772-1 clause 6.5.

From C++ 2017 forward, casting a value to an enumeration type is undefined behavior unless the source value is within the range of values of an enumeration type. See CERT INT50-CPP.

6.5.2 Avoidance mechanisms for language users

To avoid the vulnerability or mitigate its ill effects, C++ software developers can: