为什么是一个无符号比字符ÿ-1 INT 1低? [英] Why is an unsigned int 1 lower than a char y -1?

查看:337
本文介绍了为什么是一个无符号比字符ÿ-1 INT 1低?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 main()
{
    unsigned x=1;
    char y=-1;

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

我预计X> Y。
但是,当我改变unsigned int类型以符号整数,我得到了预期的效果。

I expected x>y. but when i changed unsigned int to signed int, i got expected results.

推荐答案

如果字符等同于符号字符


  • 字符提升为 INT (整型的提升,ISO C99§6.3.1.1¶2)

  • 由于 INT 无符号具有相同的秩, INT 转换为无符号(算术转换,ISO C99§6.3.1.8)

  • char is promoted to int (Integer Promotions, ISO C99 §6.3.1.1 ¶2)
  • Since int and unsigned have the same rank, int is converted to unsigned (Arithmetic Conversions, ISO C99 §6.3.1.8)

如果字符等同于 unsigned char型


  • 字符可晋升为 INT unsigned int类型

    • 如果 INT 可以重新present所有 unsigned char型值(通常是因为的sizeof(int)的&GT;的sizeof(char)的),字符转换为 INT

    • 否则(通常是因为的sizeof(字符)==的sizeof(INT)),字符转换为无符号

    • char may be promoted to either int or unsigned int:
      • If int can represent all unsigned char values (typically because sizeof(int) > sizeof(char)), char is converted to int.
      • Otherwise (typically because sizeof(char)==sizeof(int)), char is converted to unsigned.

      整数优惠:
       一种较低级的 INT 是,如果转换为 INT 中的前pression INT 可以容纳所有的原始类型,值的,以无符号其他。

      Integer promotions: An expression of a type of lower rank that int is converted to int if int can hold all of the values of the original type, to unsigned otherwise.

      算术转换:
      尝试转换为更大的类型。当有冲突符号和无符号,如果较大(也包括两种类型具有相同等级的情况)类型是unsigned,去签名。否则,请只用它可以重新present所有这两种类型的值的情况下签署的。

      Arithmetic conversions: Try to convert to the larger type. When there is conflict between signed and unsigned, if the larger (including the case where the two types have the same rank) type is unsigned, go with unsigned. Otherwise, go with signed only in the case it can represent all the values of both types.

      转换为整数类型(ISO C99§6.3.1.3):

      Conversions to integer types(ISO C99 §6.3.1.3):

      超出范围的数值为无符号整数类型的转换是通过环绕(模运算)来完成。

      Conversion of an out-of-range value to an unsigned integer type is done via wrap-around (modular arithmetic).

      外的范围内的值,以一个符号整型的转换被执行的定义,并且可以提高的信号(如SIGFPE)

      Conversion of an out-of-range value to a signed integer type is implementation defined, and can raise a signal (such as SIGFPE).

      这篇关于为什么是一个无符号比字符ÿ-1 INT 1低?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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