why this would result in long integer overflow

前端 未结 5 1199
执念已碎
执念已碎 2021-02-18 18:45

I checked the document that long= int64 has range more than 900,000,000,000,000

Here is my code:

int r = 99;
long test1 = r*r*r         


        
5条回答
  •  悲哀的现实
    2021-02-18 19:18

    As the other have said, but:

    long test2 = 99L * 99 * 99 * 99 * 99;
    

    This will give you the correct result with less L around :-)

    This happens because the first 99L is a long, so all the multiplications are done in the long "field" and all the other integers are upcasted to long before the multiplication (clearly the multiplication is always between 2 numbers and it's from left to right, so it's like (((99L * 99) * 99) * 99) * 99 and each "partial" result is a long and causes the next operand to be converted to long.)

提交回复
热议问题