#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模板网!
编译器如何处理编译时分支?What do compilers do with compile-time branching?(编译器如何处理编译时分支?)
我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗Can I use if (pointer) instead of if (pointer != NULL)?(我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?)
在 C/C++ 中检查空指针Checking for NULL pointer in C/C++(在 C/C++ 中检查空指针)
比较运算符的数学式链接-如“if((5<j<=1))&quMath-like chaining of the comparison operator - as in, quot;if ( (5lt;jlt;=1) )quot;(比较运算符的数学式链接-如“if((5<j<=1)))
“if constexpr()"之间的区别与“if()"Difference between quot;if constexpr()quot; Vs quot;if()quot;(“if constexpr()之间的区别与“if())
C++,'if' 表达式中的变量声明C++, variable declaration in #39;if#39; expression(C++,if 表达式中的变量声明)