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.
这篇关于为什么如果条件无法比较负整数和正整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么如果条件无法比较负整数和正整数
基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
