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);
}
The strongly-typed enumerations have to follow stronger rules: The enumerators can only be accessed in the scope of the enumeration. The enumerators don't implicitly convert to int. The enumerators aren't imported in the enclosing scope. The type of the enumerators is by default int.
Overview. To convert an enum to int , we can: Typecast the enum value to int . Use the ToInt32 method of the Convert class.
In C++ programming, enum or enumeration is a data type consisting of named values like elements, members, etc., that represent integral constants. It provides a way to define and group integral constants. It also makes the code easy to maintain and less complex.
I recently explained that although both C and C++ provide void * as the generic data pointer type, each language treats the type a little differently. For any object type T , both C and C++ let you implicitly convert an object of type T * to void * .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With