Signed/unsigned comparisons

后端 未结 5 865
情歌与酒
情歌与酒 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:17

    The line of code in question does not generate a C4018 warning because Microsoft have used a different warning number (i.e. C4389) to handle that case, and C4389 is not enabled by default (i.e. at level 3).

    From the Microsoft docs for C4389:

    // C4389.cpp
    // compile with: /W4
    #pragma warning(default: 4389)
    
    int main()
    {
       int a = 9;
       unsigned int b = 10;
       if (a == b)   // C4389
          return 0;
       else
          return 0;
    };
    

    The other answers have explained quite well why Microsoft might have decided to make a special case out of the equality operator, but I find those answers are not super helpful without mentioning C4389 or how to enable it in Visual Studio.

    I should also mention that if you are going to enable C4389, you might also consider enabling C4388. Unfortunately there is no official documentation for C4388 but it seems to pop up in expressions like the following:

    int a = 9;
    unsigned int b = 10;
    bool equal = (a == b); // C4388
    

提交回复
热议问题