为什么是负INT比unsigned int类型更大? [英] Why is a negative int greater than unsigned int?
问题描述
INT主要(无效)
{
unsigned int类型Y = 10;
INT X = - 4;
如果(X> Y)
的printf(x大于);
其他
的printf(Y大于);
残培();
返回(0);
}输出:x大于
我想输出是y是更大,因为它是无符号。是什么原因背后?
由于该 INT
值提升到 unsigned int类型
。特别是 0xFFFFFFFC
32位的机器,它作为一个 unsigned int类型
是 4294967292 对code>,不是
10
C99 6.3.1.1-P2
如果int可以重新present(由宽度的限制,对于一个位字段)的原始类型的所有值,该值被转换为int;否则,将其转换为 unsigned int类型即可。这些被称为整数促销。所有其他类型是整数的提升不会改变。
块引用>要执行转换:
C99 6.3.1.3-P2
否则,如果新类型是无符号的值被重复地增加或减1比可以重新$ P $在新型psented直到该值是在新的类型的范围的最大值更转换
块引用>这基本上意味着增加UINT_MAX + 1(因为我读它,反正)。
至于为什么推广是对
unsigned int类型
的一面; precedence:C99 6.3.1.8-P1
...否则,如果具有无符号整型操作数的秩大于或等于另一个操作数的类型的秩,然后用符号整型操作数被转换为操作数的无符号整数的类型类型。
否则,如果有符号整数类型的操作数的类型可以重新present所有无符号整型操作数的类型的值,然后用无符号整型的操作数转换为的类型操作有符号整数类型。
块引用>这告诉我
INT
与unsigned char型
应正常工作。测试
INT的main()
{
INT X = -4;
unsigned int类型Y = 10;
unsigned char型Z = 10; 如果(X> Y)
的printf(X> Y \\ n);
其他
的printf(X< Y \\ n); 如果(X将Z)
的printf(X> Z \\ n);
其他
的printf(X< Z \\ n);
返回0;
}输出
X'GT; Y
X'LT; Z那么看看这个。
int main(void) { unsigned int y = 10; int x = – 4; if (x > y) Printf("x is greater"); else Printf("y is greater"); getch(); return (0); } Output: x is greater
I thought the output would be y is greater since it is unsigned. What's the reason behind this?
解决方案Because the
int
value is promoted to anunsigned int
. specifically0xFFFFFFFC
on a 32-bit machine, which as anunsigned int
is4294967292
, considerably larger than10
C99 6.3.1.1-p2
If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. All other types are unchanged by the integer promotions.
To perform the conversion:
C99 6.3.1.3-p2
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
Which basically means "add UINT_MAX+1" (as I read it, anyway).
Regarding why the promotion was to the
unsigned int
side; precedence:C99 6.3.1.8-p1
...Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.
Which tells me
int
vs.unsigned char
should work as expected.Test
int main() { int x = -4; unsigned int y = 10; unsigned char z = 10; if (x > y) printf("x>y\n"); else printf("x<y\n"); if (x > z) printf("x>z\n"); else printf("x<z\n"); return 0; }
Output
x>y x<z
Well look at that.
这篇关于为什么是负INT比unsigned int类型更大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!