Why does the compiler not complain about an incorrect enum value

#include <iostream> enum IsOptionAEnum { IsOptionA_YES, IsOptionA_NO }; enum IsOptionBEnum { IsOptionB_YES, IsOptionB_NO }; void TestFunc(IsOptionAEnum optionA, IsOptionBEnum optionB) { if (optionA == IsOptionA_YES || optionA == IsOptionB_YES) // typo { // ... } //if (optionA == IsOptionA_YES || optionB == IsOptionB_YES) // correct one //{ //} } 

For> optionA is of type IsOptionAEnum and does not matter IsOptionB_YES . Why does the VS2010 compiler not find this error?

If this is the case when the compiler cannot find the error, is there a way I can apply this restriction so that the compiler can find the error?

+4
source share
3 answers

Although the standard does not make this a mistake (enumerations are integer syntax), this is certainly what the compiler can detect. Clang , compiling with -Wenum-compare , gives:

 Bonsai:~ adamw$ clang++ test.cpp test.cpp:15:45: warning: comparison of two values with different enumeration types ('IsOptionAEnum' and 'IsOptionBEnum') [-Wenum-compare] if (optionA == IsOptionA_YES || optionA == IsOptionB_YES) // typo ~~~~~~~ ^ ~~~~~~~~~~~~~ 

Perhaps Visual C ++ does not warn about this by default. Try to set a flag /Wall in the compiler, which will include all the warnings. If it still does not warn, you can submit a request with the VC compiler command.

Edit: as other answers and comments were mentioned, if you have VC11, you can use Strongly typed enums .

+5
source

Pre-C ++ 11, enumeration types do not provide the required type safety and are essentially integers.

You want a strongly typed enum class:
http://www.cprogramming.com/c++11/c++11-nullptr-strongly-typed-enum-class.html

+5
source

A solution other than C ++ 11 should use struct s

 struct IsOptionAEnum { int val; static IsOptionAEnum IsOptionA_YES; static IsOptionAEnum IsOptionA_NO; IsOptionAEnum( int v ): val(v) {} }; IsOptionAEnum::IsOptionA_YES(0); IsOptionAEnum::IsOptionA_YES(1); if( optionA == IsOptionAEnum::IsOptionA_YES ) // this is type-safe // etc. 

You can reset the internal value if you do not need it (you need to disable copying, always pass by reference and compare the addresses of structures).

In C ++ 11, you can use typed enums as suggested by Prashant.

+1
source

All Articles