Search code examples
c++castingintconventions

Automatic conversion of int to unsigned int


#include <iostream>
using namespace std;

int main() {
    unsigned int u = 5;
    int x = -1;
    if(x>u) {
        cout<<"Should not happen"<<endl;
    } else {
        cout<<"Ok"<<endl;
    }
}

This code outputs Should not happen. I came across this when comparing the size of a string (size_t is an unsigned int or unsigned long long value) to an int. It seems that C type casts int to unsigned int but in practice, it seems it would bring in bugs. Honestly, I would have preferred a compile-time error given how incompatible int is to unsigned int. I would like to know why the convention is like this?


Solution

  • You can enable -Wsign-compare -Werror in Clang: Try it online!

    It'll produce a compile-time error (because of -Werror that treats warnings as errors):

    .code.tio.cpp:7:9: error: comparison of integers of different signs: 'int' and 'unsigned int' [-Werror,-Wsign-compare]
        if(x>u) {
           ~^~
    1 error generated.
    

    For some reason, -Wall -Werror in Clang (but not in GCC) doesn't produce any errors. But -Wall -Wextra -Werror does include -Wsign-compare, so you can use that.