gpt4 book ai didi

c++ - 算术转换VS积分提升

转载 作者:搜寻专家 更新时间:2023-10-31 01:37:13 25 4
gpt4 key购买 nike

char cval;
short sval;
long lval;
sval + cval; // sval and cval promoted to int
cval + lval; // cval converted to long

这是 C++ Primer 上的一段代码。我知道sval+cval根据

生成一个int类型

convert the small integral types to a larger integral type. The types bool, char, signed char, unsigned char, short, and unsigned short are promoted to int if all possible values of that type fit in an int.

但是对于最后一个我不明白为什么它使用“转换”。为什么 cval 没有首先提升为 int 然后 int 转换(或者可能提升我不确定是否可以从 intlong 因为我只看到较小类型的提升定义到 int) 到 long。在本书的那部分,我没有看到任何关于 char 直接到 long 的解释或示例。
我的理解有问题吗?
我是 C++ 的新手,有人请赐教!非常感谢!

最佳答案

加法运算符执行所谓的 usual arithmetic conversion在他们的操作数上,可以包括整数提升,然后我们可以进行进一步的转换。目的是产生一个通用类型,如果提升没有实现,则需要进一步转换。

这包含在 C++ 标准草案的 5 [expr] 部分,它说(强调我的):

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follow

并包括以下项目符号:

  • Otherwise, the integral promotions (4.5) shall be performed on both operands.61 Then the following rules shall be applied to the promoted operands:

其中有以下项目符号:

  • If both operands have the same type, 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 shall be converted to the type of the operand with greater rank.

  • Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be 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, the operand with unsigned integer type shall be converted to the type of the operand with signed integer type.
  • Otherwise, both operands shall be converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

因此在第一种情况下,在提升后它们都具有相同的类型 (int),因此不需要进一步转换。

在第二种情况下,在促销之后它们没有(int 和 long)因此需要进一步转换。

关于c++ - 算术转换VS积分提升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34486886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com