Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to cast arbitrary values of the underlying type to a strongly-typed enum type?

Tags:

c++

enums

c++11

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);
}
like image 299
R. Martinho Fernandes Avatar asked Aug 07 '11 17:08

R. Martinho Fernandes


People also ask

What is a strongly typed enum?

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.

Can you cast an enum class to int?

Overview. To convert an enum to int , we can: Typecast the enum value to int . Use the ToInt32 method of the Convert class.

What data type is enum C++?

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.

Are enums just integers?

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 * .


1 Answers

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.

like image 104
Luc Danton Avatar answered Sep 28 '22 11:09

Luc Danton