Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why compiler doesn't complain the wrong enum value

Tags:

c++

#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
    //{
    //}

}

Question> optionA is of type IsOptionAEnum and doesn't have the value of IsOptionB_YES. Why does the compiler of VS2010 not find this error?

If it is the case where compiler cannot find the error, is there a way that I can enforce this restriction so that compiler can find the error?

like image 533
q0987 Avatar asked Dec 21 '22 10:12

q0987


1 Answers

Whilst the standard doesn't render this an error (enums are effectively syntax over integers), this is certainly something a 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
                                    ~~~~~~~ ^  ~~~~~~~~~~~~~

It may be that Visual C++ doesn't warn about this by default. Try setting the /Wall flag on the compiler, which will enable all warnings. If it still doesn't warn, you can file a request with the VC compiler team.

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

like image 79
Adam Wright Avatar answered Dec 24 '22 00:12

Adam Wright