当我读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/