Following is the program that raised the mentioned doubt for me.
#include <stdio.h>
int main() {
int g = 300000*300000/300000;
printf("%d",g);
return 0;
}
When the * is evaluated the result would be 90000000000. Then is divided by 300000.
I expected the first expression result to be stored somewhere then divided by 300000. So output would be 300000.
But it is giving me -647.
Does this mean it is evaluated as :
g = 300000*300000;
g = g / 300000;
Regardless of where it’s stored, it’s still of type
int. Assumingintis 32-bits on your machine, you’re getting integer overflow with300000*300000.Basically, temporaries (or intermediates) don’t magically allow you to get around overflow.
*Note that signed integer overflow is technically undefined behavior. But in this case it happens to wrap-around the way you’d expect.