简体   繁体   中英

“long long = int + int ” first calculate ,then type conversion?

when i read caspp, there is a question that determine whether arguments can be added without overflow.so i write follow codes.

//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;
}

however , there are some question. when i assume x = -2147483647,y=-2,both sum1 and sum2 equal 2147483747(both overflow!).

And i guess ,for "long long = int + int ",first calculate ,then type conversion? so what are these rules?

The primary purpose in

long long int sum1 = x + y;

is to evaluate the expression x + y .
Note that ; is a sequence point which means any side-effect of the expression must be performed on reaching that point.
Here the side-effect is to assign the value of the expression x + y to sum1

ISO/IEC 9899:201x->6.3.1.8->1 states that :

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.

What you wish to do is

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM