为什么下面的代码打印 "S is Bigger" 即使 s 更小?
Why the following code does print "S is Bigger" even though s is smaller?
以下代码片段未按预期运行,在 Ubuntu 机器中使用 GCC 编译时,以下程序的输出为 "S is Bigger"。虽然变量 s 是 -1 并且明显小于 sizeof(buffer) 20。但它仍然打印 S is Bigger.
我能做出的唯一合乎逻辑的假设是 C 正在将变量 "s" 转换为无符号整数并在 "If" 条件下使用。
如果我的假设是正确的,为什么 C 会这样做,或者如果我错了,为什么这个片段会给出这个令人困惑的输出。
#include <stdio.h>
int main(void) {
int s = -1;
char buffer[20];
if(s > sizeof(buffer)){
printf("S is Bigger");
}
return 0;
}
来自this问题的答案
It's safe provided the int is zero or positive. If it's negative, and size_t is of equal or higher rank than int, then the int will be converted to size_t and so its negative value will instead become a positive value.
sizeof() returns size_t
你是对的,编译器将 s
转换为 unsigned int
数据类型 size_t
(即 sizeof 运算符的 return 值)。所以比较变成(在我的系统上 size_t 是 64 位):
if (18446744073709551615 > 20)
这显然是正确的 ;)
这是标准定义的隐式转换的一部分。相关部分是标准 6.3.1.8 中的“常规算术转换”。
另请参阅此 post and this other
基本规则:
- 如果两个操作数的类型相同,则不需要进一步转换。
- 如果两个操作数都是相同的整数类型(有符号或无符号),则将具有较小整数转换等级的操作数转换为具有较高等级的操作数的类型。
- 如果无符号整数类型的操作数的秩大于或等于另一个操作数类型的秩,则有符号整数类型的操作数转换为无符号整数类型的操作数的类型。
- 如果有符号整数类型操作数的类型可以表示无符号整数类型操作数类型的所有值,则无符号整数类型操作数转换为有符号整数类型操作数类型.
- 否则,将两个操作数都转换为与带符号整数类型的操作数类型对应的无符号整数类型。
以下代码片段未按预期运行,在 Ubuntu 机器中使用 GCC 编译时,以下程序的输出为 "S is Bigger"。虽然变量 s 是 -1 并且明显小于 sizeof(buffer) 20。但它仍然打印 S is Bigger.
我能做出的唯一合乎逻辑的假设是 C 正在将变量 "s" 转换为无符号整数并在 "If" 条件下使用。 如果我的假设是正确的,为什么 C 会这样做,或者如果我错了,为什么这个片段会给出这个令人困惑的输出。
#include <stdio.h>
int main(void) {
int s = -1;
char buffer[20];
if(s > sizeof(buffer)){
printf("S is Bigger");
}
return 0;
}
来自this问题的答案
It's safe provided the int is zero or positive. If it's negative, and size_t is of equal or higher rank than int, then the int will be converted to size_t and so its negative value will instead become a positive value.
sizeof() returns size_t
你是对的,编译器将 s
转换为 unsigned int
数据类型 size_t
(即 sizeof 运算符的 return 值)。所以比较变成(在我的系统上 size_t 是 64 位):
if (18446744073709551615 > 20)
这显然是正确的 ;)
这是标准定义的隐式转换的一部分。相关部分是标准 6.3.1.8 中的“常规算术转换”。
另请参阅此 post and this other
基本规则:
- 如果两个操作数的类型相同,则不需要进一步转换。
- 如果两个操作数都是相同的整数类型(有符号或无符号),则将具有较小整数转换等级的操作数转换为具有较高等级的操作数的类型。
- 如果无符号整数类型的操作数的秩大于或等于另一个操作数类型的秩,则有符号整数类型的操作数转换为无符号整数类型的操作数的类型。
- 如果有符号整数类型操作数的类型可以表示无符号整数类型操作数类型的所有值,则无符号整数类型操作数转换为有符号整数类型操作数类型.
- 否则,将两个操作数都转换为与带符号整数类型的操作数类型对应的无符号整数类型。