Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

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

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 >= 0 is always true

Here's the full code, via cat ft_memmove.c:

#include "libft.h"
#include <string.h>

void    *ft_memmove(void *s1, const void *s2, size_t n)
{
    char    *s1c;
    char    *s2c;
    size_t  i;

    if (!s1 || !s2 || !n)
    {
        return s1;
    }
    i = 0;
    s1c = (char *) s1;
    s2c = (char *) s2;
    if (s1c > s2c)
    {
        while (n - i >= 0) // this triggers the error
        {
            s1c[n - i] = s2c[n - i];
            ++i;
        }
    }
    else
    {
        while (i < n)
        {
            s1c[i] = s2c[i];
            ++i;
        }
    }
    return s1;
}

I do understand that size_t is unsigned and that both integers will be >= 0 because of that. But since I'm subtracting one from the other, I don't get it. Why does this error come up?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...