Search code examples
c++enumscomparisonintegerunsigned

C++ enum to unsigned int comparison


I found this in the code I'm working on at the moment and thought it was the cause of some problems I'm having.

In a header somewhere:

enum SpecificIndexes{
    //snip
    INVALID_INDEX = -1
};

Then later - initialization:

nextIndex = INVALID_INDEX;

and use

if(nextIndex != INVALID_INDEX)
{
    //do stuff
}

Debugging the code, the values in nextIndex didn't quite make sence (they were very large), and I found that it was declared:

unsigned int nextIndex;

So, the initial setting to INVALID_INDEX was underflowing the unsigned int and setting it to a huge number. I assumed that was what was causing the problem, but looking more closely, the test

if(nextIndex != INVALID_INDEX)

Was behaving correctly, i.e, it never executed the body of the if when nextIndex was the "large +ve value".

Is this correct? How is this happening? Is the enum value being implicitly cast to an unsigned int of the same type as the variable, and hence being wrapped in the same way?


Solution

  • Yes to everything. It is valid code, it is also commonly used library-side C++ code, more so in modern C++ (it is strange when you see it the first time but its a very common pattern in reality).

    Then enums are signed ints, but they get implicitly cast into unsigned ints, now this depending on your compiler might give a warning, but its still very commonly used, however you should explicitly cast to make it clear to maintainers.