c - 在 C 中比较不同数据类型的一般规则是什么?

标签 c comparison types

假设我有以下场景:

int i = 10;
short s = 5;

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

当 C 进行比较时,它会将较小的数据类型(在本例中为 short )转换为 int 还是将右侧的数据类型转换为左侧的数据类型? 在这种情况下是做空吗?

最佳答案

这由通常的算术转换 控制。对于简单的情况,一般的经验法则是将精度“较低”的类型转换为与精度“较高”的类型相匹配,但是一旦开始混合使用 signed,它就会变得有些复杂>未签名

在 C99 中,这在第 6.3.1.8 节中进行了描述,为了您的方便,我将其包含在这里:

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

  • 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:

    • If both operands have the same type, then no further conversion is needed.
    • Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
    • 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.
    • Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

我已经突出显示了适用于您的特定示例的部分。

整数转换等级的概念在第 6.3.1.1 节中定义,它基本上描述了您可能期望的内容(精度较低的类型的等级低于精度较高的类型)。

关于c - 在 C 中比较不同数据类型的一般规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6636793/

相关文章:

python - 使用 Python 检测 C 文件中的递归

c - 释放字符串中的内存释放 "invalid next size (fast)"

wpf - 在 WPF 中,我如何限制面板中子项的类型?

c++ - 迭代不同类型 vector 的索引类型

c - Typedef 缺少类型说明符

c - 在 C 中,数组定义中的长度如何映射到寻址?

python - 如何理解Python中的 `3<range(3)`

multithreading - 多线程二进制差异工具?

c# - 满足特定条件的 Array.BinarySearch

c# - 如何在 C# 中创建关键字/类型?