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
", 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.
这篇关于为什么如果条件无法比较负整数和正整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么如果条件无法比较负整数和正整数


基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01