为什么会出现这种情况,如果失败的消极和积极的整数比较 [英] Why does this if condition fail for comparison of negative and positive integers
问题描述
#include <stdio.h>
int arr[] = {1,2,3,4,5,6,7,8};
#define SIZE (sizeof(arr)/sizeof(int))
int main()
{
printf("SIZE = %d\n", SIZE);
if ((-1) < SIZE)
printf("less");
else
printf("more");
}
与 GCC
编译后的输出是更多
。为什么如果
一条件,则即使 -1 LT; 8
?
The output after compiling with gcc
is "more"
. Why the if
condition fails even when -1 < 8
?
推荐答案
问题是在你的比较:
if ((-1) < SIZE)
的sizeof
通常返回无符号长
,所以尺寸
将无符号长
,而 1
只是一个 INT
。在C和相关语言晋升的规则意味着-1将在比较之前被转换成为size_t
,所以 1
将成为一个非常大的正值(一个无符号长
)。
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 ...
编译器会提醒你你的bug。
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.
这篇关于为什么会出现这种情况,如果失败的消极和积极的整数比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!