Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

long long int ans = a*b VS long long int ans = (long long int) a*b

Tags:

c++

I've written a code:

int a = 1000000000, b = 1000000000;
long long int ans = a * b;
cout << ans << '\n';

this code is causing overflow. I understand that a * b is causing the problem but I have taken long long int variable to keep a*b. But look at the following code:

int a = 1000000000, b = 1000000000;
long long int ans = (long long int)a * b;
cout << ans << '\n';

it's working fine causing no overflow. Does it make any temporary variable to hold the value when calculating? Please explain the reason behind this strange overflowing.

like image 690
Jahirul Sarker Avatar asked Oct 29 '25 14:10

Jahirul Sarker


1 Answers

This makes two temporary variables, (long long int)a and (long long int)b. The second conversion is implicit.

Actual compilers might not bother, if the hardware has a 32*32->64 multiply, but officially the conversions have to occur. On 64 bits hardware, it's essentially free when you load an int in a 64 bit register.

like image 92
MSalters Avatar answered Oct 31 '25 03:10

MSalters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!