C++ Signed/unsigned mismatch

The signed/unsigned nature of the two values you are comparing should be the same, otherwise one gets cast as the other for the comparison, which can lead to unexpected results.

It would be best to make sure that what you’re comparing are the same type, but:

If you know which value is safe to cast, explicitly cast that one. In your case, case the signed value as an unsigned value.

e.g.

unsigned int val1 = someunsignedvalue;  
int val2 = somesignedvalue;    
if (val1 > (unsigned int) val2) {
    /* do stuff */  
}

Leave a Comment