什么是用C比较不同数据类型的一般规则? [英] What are the general rules for comparing different data types in C?

查看:133
本文介绍了什么是用C比较不同数据类型的一般规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有以下情况:

int i = 10;
short s = 5;

if (s == i){
   do stuff...
} else if (s < i) {
  do stuff...
}

当C那样被比较它转换更小的数据类型,在这种情况下,短到int或它转换到左边的数据类型的权利的数据类型?
在这种情况下int到short?

When C does the comparison does it convert the smaller data type, in this case short to int or does it convert the data type on the right to the data type on the left? In this case int to short?

推荐答案

这是由的通常的算术转换管辖的。对于简单的情况下,一般的经验法则是,与少precision的类型转换,以配合多precision类型,但一旦你开始混合它变得有点复杂签署无符号

This is governed by the usual arithmetic conversions. For simple cases, the general rule of thumb is that the type with "less" precision is converted to match the type with "more" precision, but it gets somewhat complex once you start mixing signed and unsigned.

在C99,这是由部分6.3.1.8,这是我在这里包括为方便您描述的:

In C99, this is described by section 6.3.1.8, which I include here for your convenience:


      
  • 首先,如果相应的实型操作数是长双
      另一个操作数转换,
      无类域的变化,一
      相应的实型类型,其是
      长双

否则,如果相应的实型操作数是双击
  另一个操作数转换,
  无类域的变化,一
  相应的实型类型,其是
  双击

Otherwise, if the corresponding real type of either operand is double, the other operand is converted, without change of type domain, to a type whose corresponding real type is double.

否则,如果相应的实型操作数是浮动
  另一个操作数转换,
  无类域的变化,一
  相应的实型类型,其是
  浮动

Otherwise, if the corresponding real type of either operand is float, the other operand is converted, without change of type domain, to a type whose corresponding real type is float.

另外,整数促销活动是在两个操作数执行。然后
  以下规则被施加到
  提升操作数:

Otherwise, the integer promotions are performed on both operands. Then the following rules are applied to the promoted operands:


      
  • 如果两个操作数具有相同的类型,则没有进一步转化为
      必要的。

  •   
  • ,否则,如果两个操作数有符号整数类型或两者都有
      无符号整型,操作数
      具有较低整数的种类
      转换秩被转化为
      类型有更大级别的操作数的。

  •   
  • 否则,如果具有无符号整型操作数的秩
      大于或等于的秩
      类型其他操作,那么
      操作与符号整数类型
      转换到操作数的类型
      与无符号整型。

  •   
  • 否则,如果操作数的带符号整数类型的类型可以
      再present所有的值
      无符号操作数的类型
      整数类型,则操作数与
      无符号整型转换为
      与签订了操作数的类型
      整数类型。

  •   
  • 否则,两个操作数都转换为无符号整型
      对应的类型
      操作有符号整数类型。

  •   

我已经强调了适用于您的具体的例子的部分。

I've highlighted the part that applies to your particular example.

的概念的整数转换等级的是在第6.3.1.1定义,它基本上描述你所期望的(即类型较少precision比种较低的等级更precision)。

The concept of integer conversion rank is defined in section 6.3.1.1, and it basically describes what you might expect (that types with less precision have a lower rank than types with more precision).

这篇关于什么是用C比较不同数据类型的一般规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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