what does the signed/unsigned comparison warning mean?

前端 未结 5 440
南旧
南旧 2021-01-29 06:42
auto.cpp: In function ‘int autooo(unsigned int)’:
auto.cpp:33:25: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]

相关标签:
5条回答
  • 2021-01-29 07:01

    It says you are comparing two different things. Most notably the range of one does not fit into the range of another.

    I.e there. Exists a number in the unsigned range that cannot be expressed as a signed number

    0 讨论(0)
  • 2021-01-29 07:06

    At this line

    while (numberFound < b);

    The first is an unsigned int and the second an int. So you have to make them the same type, or if you are completely sure cast one of them.

    As Etan commented:

    "Blindly casting away a warning just to avoid the warning is a mistake. You need to understand what the warning is telling you and decide what the right fix is."

    0 讨论(0)
  • 2021-01-29 07:07

    Type cast the code before you were comparing the signed and unsigned code to avoid warning

    int a;
    unsigned int b;
    
    if(a==b) gives warning
    
    if(a == (int)b)
    

    will resolve your issue

    EDIT

    Blind casting will lead to some unexpected results

    The warning is because ranges for signed and unsigned are different.

    Casting will work fine when signed integer you were used for comparison was greater than zero.

    so have check whether the signed integer is greater that zero before comparing

    More info here

    0 讨论(0)
  • 2021-01-29 07:10

    The compiler warns that the code contains comparison of unsigned int with a signed int in the line

    while (numberFound < b);
    

    This has nothing to do with makefiles or make.

    You can fix that by changing

    int b=50;
    

    to

    unsigned b = 50;
    

    or by changing

    unsigned numberFound = 0;
    

    to

    int numberFound = 0;
    

    The problems you might run into when comparing signed int and unsigned int are explained in this answer to another SO question

    0 讨论(0)
  • 2021-01-29 07:10

    You are getting this warning about comparing signed and unsigned types because the ranges of signed and unsigned ints are different. If you have to make such a comparison, you should explicitly cast one of the values to be compatible with the other, but a check is required to make sure value your cast is valid.

    For e.g:-

    int i = someIntValue();
    
    if (i >= 0)
    {
        // i is non-negative, so it is safe to compare to unsigned value
        if ((unsigned)i >= u)
            // do something
    }
    
    0 讨论(0)
提交回复
热议问题