Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting enum to enum via int in C++

Tags:

c++

enums

Is it valid to convert an enum to a different enum via int conversion, like illustrated below ? It looks like gcc for x64 has no problem with it, but is it something to expect with other compilers and platforms as well ?

What happens when a equals A_third and has no equivalent in enum_B ?

enum enum_A {
    A_first = 0,
    A_second,
    A_third
};

enum enum_B {
    B_first = 0,
    B_second
};

enum_A a = A_first;
enum_B b;

b = enum_B(int(a)); 
like image 783
antou Avatar asked Sep 19 '25 22:09

antou


1 Answers

You have to be careful when doing this, due to some edge cases:

From the C++11 standard (§7.2,6):

For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration. If no integral type can represent all the enumerator values, the enumeration is ill-formed. It is implementation-defined which integral type is used as the underlying type except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int.

This means that it is possible that an enum is a larger type than an int so the conversion from enum to int could fail with undefined results.

Subject to the above, it is possible to convert an int to an enum that results in an enumerator value that the enum does not specify explicitly. Informally, you can think of an enum as being an integral type with a few values explicitly defined with labels.

like image 166
Bathsheba Avatar answered Sep 22 '25 13:09

Bathsheba