为什么负整数大于无符号整数? [英] Why is a negative int greater than unsigned int?

查看:40
本文介绍了为什么负整数大于无符号整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我认为输出 y 会更大,因为它是无符号的.这背后的原因是什么?

I thought the output would be y is greater since it is unsigned. What's the reason behind this?

推荐答案

因为 int 值被提升为 unsigned int.特别是在 32 位机器上的 0xFFFFFFFC,作为 unsigned int4294967292,远大于 10

Because the int value is promoted to an unsigned int. specifically 0xFFFFFFFC on a 32-bit machine, which as an unsigned int is 4294967292, considerably larger than 10

C99 6.3.1.1-p2

如果 int 可以表示原始类型的所有值(受宽度限制,对于位域),则该值将转换为 int;否则,它将被转换为 unsigned int.这些被称为整数促销.整数提升不会改变所有其他类型.

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.

执行转换:

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.

这基本上意味着添加 UINT_MAX+1";(无论如何,正如我所读的那样).

Which basically means "add UINT_MAX+1" (as I read it, anyway).

关于为什么推广到 unsigned int 方面;优先级:

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.

这告诉我 intunsigned char 应该按预期工作.

Which tells me int vs. unsigned char should work as expected.

测试

int main()
{
    int x = -4;
    unsigned int y = 10;
    unsigned char z = 10;

    if (x > y)
        printf("x>y
");
    else
        printf("x<y
");

    if (x > z)
        printf("x>z
");
    else
        printf("x<z
");
    return 0;
}

输出

x>y
x<z

看看那个.

这篇关于为什么负整数大于无符号整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆