what does the signed/unsigned comparison warning mean?

前端 未结 5 628
南旧
南旧 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: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
    }
    

提交回复
热议问题