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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With