C++ Enums C++11 – Is It Safe to Cast Arbitrary Values to Strongly-Typed Enum?

c++c++11enums

If I have a strongly-typed enum, with say, underlying type int, is it ok to cast an int value that does not match any enumerator to the enum type?

enum e1 : int { x = 0, y = 1 };
enum class e2 : int { x = 0, y = 1 };

int main() {
        e1 foo = static_cast<e1>(42); // is this UB?
        e2 bar = static_cast<e2>(42);
}

Best Answer

From n3290, 5.2.9 Static cast [expr.static.cast]:

10 A value of integral or enumeration type can be explicitly converted to an enumeration type. The value is unchanged if the original value is within the range of the enumeration values (7.2). Otherwise, the resulting value is unspecified (and might not be in that range). [...]

Enumeration type comprises both those types that are declared with enum and those that are declared with enum class or enum struct, which the Standard calls respectively unscoped enumerations and scoped enumerations. Described in more details in 7.2 Enumeration declarations [dcl.enum].

The values of an enumeration type are not be confused with its enumerators. In your case, since the enumerations you declared all have int as their underlying types their range of values is the same as that of int: from INT_MIN to INT_MAX (inclusive).

Since 42 has type int and is obviously a value of int the behaviour is defined.