warning: comparison of unsigned expression >= 0 is always true

前端 未结 5 1239
野性不改
野性不改 2020-12-11 23:23

I have the following error when compiling a C file:

t_memmove.c: In function ‘ft_memmove’:
ft_memmove.c:19: warning: comparison of unsigned expression >=          


        
相关标签:
5条回答
  • 2020-12-11 23:47

    If you subtract two unsigned integers in C, the result will be interpreted as unsigned. It doesn't automatically treat it as signed just because you subtracted. One way to fix that is use n >= i instead of n - i >= 0.

    0 讨论(0)
  • 2020-12-11 23:50

    Operations with unsigned operands are performed in the domain of unsigned type. Unsigned arithmetic follows the rules of modular arithmetic. This means that the result will never be negative, even if you are subtracting something from something. For example 1u - 5u does not produce -4. If produces UINT_MAX - 3, which is a huge positive value congruent to -4 modulo UINT_MAX + 1.

    0 讨论(0)
  • 2020-12-11 23:54

    According to section 6.3.1.8 of the draft C99 standard Usual arithmetic conversions, since they are both of the same type, the result will also be size_t. The section states:

    [...]Unless explicitly stated otherwise, the common real type is also the corresponding real type of the result[...]

    and later on says:

    If both operands have the same type, then no further conversion is needed.

    mathematically you can just move the i over to the other side of the expression like so:

     n >= i
    
    0 讨论(0)
  • 2020-12-12 00:07

    Arithmetic on unsigned results in an unsigned and that's why you are getting this warning. Better to change n - i >= 0 to n >= i.

    0 讨论(0)
  • 2020-12-12 00:10

    consider this loop:

    for(unsigned int i=5;i>=0;i--)
    {
    
    }
    

    This loop will be infinite because whenever i becomes -1 it'll be interprated as a very large possitive value as sign bit is absent in unsigned int.

    This is the reason a warning is generated here

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