int和short在c中的行为 [英] Behavior of int and short in c

查看:142
本文介绍了int和short在c中的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下代码输出的原因:

I want to know what is the reason of the output of the following codes:

unsigned short a=10,aa=-1;
if(a>-1)
  printf("surprise");
else 
  printf(" No surprise");

这将提供输出惊喜"

 unsigned int a=10,aa=-1;
    if(a>-1)
      printf("surprise");
    else 
      printf("No surprise");

这将给出输出"No Surprise"

This gives output "No Surprise"

unsigned short a=10,aa=-1;
if(a>aa)
   printf("surprise");
else 
  printf("No surprise");

这将给出输出"No Surprise"

This gives the output "No Surprise"

推荐答案

请参阅此Stack Exchange问​​题:

See this Stack Exchange question:

在一个存在unsigned int和signed int的C表达式,哪种类型将被提升为哪种类型?

在AProgrammer的响应中,列出了完整的规则. 在第一种情况下,将应用第4条规则(-1是有符号整数,可以表示无符号short的所有值,因此无符号short被提升为有符号整数). 在第二种情况下,将应用第三条规则(有符号整数不能代表无符号整数的所有值,因此将其更改为无符号整数). 在您的第三种情况下,-1转换为无符号short,然后应用第一条规则.

In the response from AProgrammer, the complete rules are listed. In your first case, the 4th rule applies (-1 is signed integer, which can represent all the values of unsigned short, therefore the unsigned short is promoted to signed integer). In your second case, the 3rd rule applies (signed integer cannot represent all values of unsigned integer, so it is changed to unsigned integer). In your third case, the -1 is converted to unsigned short and then the first rule applies.

通常,我希望通过在进行任何比较之前将所有var转换为相同的有符号类型(足够大以容纳我期望的范围)来避免混淆.

In general I like to avoid confusion by converting all vars to the same signed type (large enough to hold the range I expect) before doing any comparisons.

这篇关于int和short在c中的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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