警告:无符号表达式> = 0的比较始终为true [英] warning: comparison of unsigned expression >= 0 is always true
问题描述
编译C文件时出现以下错误:
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
这是完整的代码,通过cat ft_memmove.c
:
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;
}
我确实知道size_t是无符号的,因此两个整数都将> = 0.但是由于我要从另一个中减去一个,所以我不明白.为什么会出现此错误?
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?
推荐答案
如果在C中减去两个无符号整数,则结果将被解释为无符号.它不会仅仅因为您减去就自动将其视为带符号.解决此问题的一种方法是使用n >= i
而不是n - i >= 0
.
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的比较始终为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!