1

Consider this code:

typedef enum Type1 { val11, val12 } Type1; typedef enum Type2 { val21, val22 } Type2; Type1 type1 = val11; if ( type1 == val22 ) std::cout << "foo"; 

Visual Studio 2015 does not issue any warning (even with /Wall). However type1 and val22 are not of the same type. Is that normal or is it a Visual Studio bug?

6
  • if it's anything like c# enums are just backed by an integer, so if that holds true in c++ it could perhaps be equivalent to if (type1 == 1) Commented Nov 30, 2016 at 16:52
  • That's normal. Both sides of the equality operator are cast to int. Commented Nov 30, 2016 at 16:52
  • 3
    Write modern C++ code, use enum class. Commented Nov 30, 2016 at 16:53
  • 1
    The typedef is useless here unless the enum definitions are also compiled in C. Commented Nov 30, 2016 at 17:07
  • @HansPassant: Would that trigger a compilation warning/error? Could you post this as an answer with an example? Commented Nov 30, 2016 at 18:06

1 Answer 1

0

As far as I know, the compiler does not have obligation to issue a warning when comparing enumerations of different types. I could not find it in the standard. For classic enum types there exist implicit type conversion to int, so the resulting code is perfectly legal. Semantically it is often incorrect to compare enumerations of different types, so since C++ we have a scoped enumeration construction which does not allow implicit conversions. (See the code below).

#include <iostream> using namespace std; enum UE1 // This is an unscoped enumeration (since C) { val11, val12 }; enum UE2 // This is an unscoped enumeration too { val21, // have to use different names for enumeration constants val22 }; enum class SE1 // This is an scoped enumeration (since C++11) { val1, val2 }; enum class SE2 { val1, // can use the same names for the constants val2 // because they are in the different scope }; int main(int, char**) { if (val11 == val22) // implicit conversion from an enum to int is available cout << "UE::val11 is equal to UE::val22" << endl; if (static_cast<int>(SE1::val1) == static_cast<int>(SE2::val1)) // have to apply explicit conversion cout << "SE1::val1 is equal to SE2::val1" << endl; if (SE1::val1 == SE2::val1) // error!!! Cannot make implicit conversions from a scoped enumeration. cout << "SE1::val1 is equal to SE2::val1" << endl; return 0; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.