Why Is Comparing if an Unsigned Int >= 0 a “Pointless Comparison”?

后端 未结 10 1726
情话喂你
情话喂你 2021-02-12 10:44

I got warning:

Pe186 \"Pointless comparison of unsigned int with zero\"

when I tried to compile the following code:



        
相关标签:
10条回答
  • 2021-02-12 10:48

    clLoop >= 0 is always true. It doesn't matter whether you pre-decrement or post-decrement, an unsigned value is at least 0. When you decrement 0 you get UINT_MAX.

    The compiler figures that you probably don't mean to loop forever (or you'd have used a different construct, that more obviously loops forever), hence the warning.

    0 讨论(0)
  • 2021-02-12 10:49

    You check whether the unsigned int is greater than or equal (>=) zero. This expression will always be true, because unsigned integers will never be less than zero.

    The compiler tries to warn you that you are about to program an infinite loop.

    0 讨论(0)
  • 2021-02-12 10:58

    An unsigned integer never falls below 0 even after decrementing infinitely (i.e. clLoop >= 0 will always be true), which makes the comparison pointless.

    0 讨论(0)
  • 2021-02-12 10:58

    As already stated by others unsigned int is always >= 0 i.e. pointless comparison. Mayank Jindal posted for me the starting point for a solution.

    To document the "fix" as a whole: do the following instead, this works as intended:

    unsigned int cpLoopStart = 23U;
    unsigned int clLoop = 0U;
    for(clLoop = cpLoopStart; clLoop > 0U; clLoop--}
    {
        //Do something
    }
    

    clLoop will start at 23 and end at 1 then exits the loop. I hope it was intended that clLoop will never be 0 inside the loop.

    I also prefer to append "U" for unsigned typed values, this makes is clearer also when comparing values and variables.

    0 讨论(0)
  • 2021-02-12 11:00

    gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-11) in Centos 7 x86_64 does not give the warning.

    But when loop index is decremented to -1, loop index is implicitly converted to a value which is equal to UINT_MAX (limits.h)

    UINT_MAX + 1u is equal to 0. 0 - 1 is equal to UINX_MAX.

    limits.h Various platform-dependent constants proposed by ANSI

    One of alternative solution is:

    unsigned int clLoop, i;
    
    for(i = cpLoopStart+1, clLoop = i-1; i > 0; i--, clLoop = i-1)                                  
    {
        //Do something
    }
    

    i will change in the range [1, cpLoopStart+1]

    clLoop will change in the range [0, cpLoopStart]

    0 讨论(0)
  • 2021-02-12 11:02

    You are checking if an unsigned int is equal or greater than 0. Which is always true.

    0 讨论(0)
提交回复
热议问题