ccompiler-warningsunsignedsigned

Should I disable the C compiler signed/unsigned mismatch warning?


The Microsoft C compiler warns when you try to compare two variables, and one is signed, and the other is unsigned. For example:

int a;    
unsigned b;

if ( a < b ) { // warning C4018: '&lt;' : signed/unsigned mismatch

}

Has this warning, in the history of the world, ever caught a real bug? Why's it there, anyway?


Solution

  • Oh it has. But the other way around. Ignoring that warning caused a huge headache to me one day. I was writing a function that plotted a graph, and mixed signed and unsigned variables. In one place, i compared a negative number to a unsigned one:

    int32_t t; ...
    uint32_t ut; ...
    
    if(t < ut) { 
        ...
    }
    

    Guess what happened? The signed number got promoted to the unsigned type, and thus was greater at the end, even though it was below 0 originally. It took me a couple of hours until i found the bug.