考虑这个C代码:为什么C不运行unsigned int与负值的比较?
#include "stdio.h"
int main(void) {
int count = 5;
unsigned int i;
for (i = count; i > -1; i--) {
printf("%d\n", i);
}
return 0;
}
我的观察/问题:循环永远不会被执行。但是,如果我将数据类型从unsigned int更改为int,则所有内容都按预期工作。
我一直在考虑未签名的整数作为值,“环绕”,当你试图保持减去他们。所以,当我是零,我减1,它会绕到UINT_MAX。而且由于它的价值从不消极,所以这将是一个无限循环。 (而这正是当我将比较从i> -1改变为i> = 0时发生的情况。)
我的逻辑中某处出现故障,因为如果我是无符号的,循环永远不会执行,而且我将它与-1进行比较。编译器会以某种方式优化它,或者运行时值的行为与我期望的不同。
为什么循环不能运行?
您是否尝试过直接转换字面值-1? – 0xC0000022L 2011-06-02 17:17:11
你是完全正确的。但请记住,5> UINT_MAX是错误的。 – sidyll 2011-06-02 17:18:29
http://stackoverflow.com/questions/2084949/arithmetic-operations-on-unsigned-and-signed-integers http://stackoverflow.com/questions/24466857/why-sizeofint-is-not-greater-than- 1 http://stackoverflow.com/questions/3100365/why-is-%E2%88%921-sizeofint – 2015-03-24 11:59:15