#include <stdio.h>
int arr[] = {1,2,3,4,5,6,7,8};
#define SIZE (sizeof(arr)/sizeof(int))
int main()
{
printf("SIZE = %d
", SIZE);
if ((-1) < SIZE)
printf("less");
else
printf("more");
}
用gcc
编译后的输出是"more"
.为什么即使 -1
-1
条件也会失败?8
?
The output after compiling with gcc
is "more"
. Why the if
condition fails even when -1 < 8
?
问题在于你的比较:
if ((-1) < SIZE)
sizeof
通常返回一个 unsigned long
,所以 SIZE
将是 unsigned long
,而 -1
只是一个 int
.C及相关语言的提升规则是-1会在比较前转换为size_t
,所以-1
会变成一个非常大的正值(最大值unsigned long
).
sizeof
typically returns an unsigned long
, so SIZE
will be unsigned long
, whereas -1
is just an int
. The rules for promotion in C and related languages mean that -1 will be converted to size_t
before the comparison, so -1
will become a very large positive value (the maximum value of an unsigned long
).
解决此问题的一种方法是将比较更改为:
One way to fix this is to change the comparison to:
if (-1 < (long long)SIZE)
尽管这实际上是一个毫无意义的比较,因为根据定义,无符号值总是 >= 0,并且编译器很可能会就此警告您.
although it's actually a pointless comparison, since an unsigned value will always be >= 0 by definition, and the compiler may well warn you about this.
正如@Nobilis 随后指出的那样,您应该始终启用编译器警告并注意它们:如果您使用例如编译gcc -Wall ...
编译器会警告你你的错误.
As subsequently noted by @Nobilis, you should always enable compiler warnings and take notice of them: if you had compiled with e.g. gcc -Wall ...
the compiler would have warned you of your bug.
这篇关于为什么如果条件无法比较负整数和正整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!