4

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)); 
5
  • 2
    What happens when a equals A_third and has no equivalent in enum_B ? What would you like to happen. Surely you realise that what you are attempting is fundamentally wrong. What are you trying to achieve here. Commented Dec 12, 2014 at 11:41
  • @JoachimPileborg, Are you sure it's UB? We're not talking about the stronger enumeration types in C++11. Commented Dec 12, 2014 at 11:48
  • My understanding is, that if it doesn't overflow the implied integral type of the enum, then you get an unlabelled enumeration value; and that's well-defined. Commented Dec 12, 2014 at 11:51
  • @Bathsheba You're probably right, and I don't have the specification readily available at the moment so I can't check, so I'll retract my comments. Commented Dec 12, 2014 at 11:53
  • @DavidHeffernan : Yes, I realize this is awfully wrong. I'm just curious as to what should actually happen during execution: will the program crash with an error, will it fail silently and continue with an unpredictable value, ... Commented Dec 12, 2014 at 12:02

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.