c++ - "long long = int + int "先计算,再类型转换?

标签 c++ c

当我读caspp时,有一个问题,确定是否可以在不溢出的情况下添加参数。所以我编写了以下代码。

//sum1 is long long ,so there is no overflow.
//when sum2 is overflow ,then sum1 != sum2;
int tadd_ok (int x,int y)
{
long long int sum1 = x + y;
int sum2 = x + y;
return sum1 == sum2;
}

但是,还有一些问题。 当我假设x = -2147483647,y=-2时,sum1和sum2都等于2147483747(都溢出!)。

我猜,对于“long long = int + int”,先计算,然后类型转换? 那么这些规则是什么?

最佳答案

主要目的

long long int sum1 = x + y;

是计算表达式x + y
请注意,;是一个序列点,这意味着表达式的任何副作用都必须在达到该点。
这里的副作用是将表达式x + y的值分配给sum1

ISO/IEC 9899:201x->6.3.1.8->1 规定:

Unless explicitly sstated otherwise, the common real type is also the corresponding real type of the result..
..
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.

你想做的是

long long int sum1 = (long long int)x + y; // Casting x to LL causes y to be auto-converted

关于c++ - "long long = int + int "先计算,再类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38517422/

相关文章:

c - 读取一个字符串并将其放入C中的(int)中

c++ - 在堆栈上创建对象

c++ - 为什么我可以在 C 中将 int 文字隐式转换为 int * 而在 C++ 中却不能?

c++ - 从 Qt 中的 QInputDialog 获取多个输入

c++ - 在另一个 C++ 中调用一个类的方法

c - 为什么在链表中插入节点后返回指针

c++ - 改进dll丢失错误信息

C : erroneous output for "(long long int) = (long long int) * (double)"?

c - 内存管理c

objective-c - getchar() 不按 'enter' 按钮