Signed/unsigned comparisons

后端 未结 5 796
情歌与酒
情歌与酒 2020-11-22 06:29

I\'m trying to understand why the following code doesn\'t issue a warning at the indicated place.

//from limits.h
#define UINT_MAX 0xffffffff /* maximum unsi         


        
5条回答
  •  醉话见心
    2020-11-22 07:32

    Why signed/unsigned warnings are important and programmers must pay heed to them, is demonstrated by the following example.

    Guess the output of this code?

    #include 
    
    int main() {
            int i = -1;
            unsigned int j = 1;
            if ( i < j ) 
                std::cout << " i is less than j";
            else
                std::cout << " i is greater than j";
    
            return 0;
    }
    

    Output:

    i is greater than j
    

    Surprised? Online Demo : http://www.ideone.com/5iCxY

    Bottomline: in comparison, if one operand is unsigned, then the other operand is implicitly converted into unsigned if its type is signed!

提交回复
热议问题