I wrote some code to find whether the multiplication of two integers will result in overflow or not. And can the result be stored as an integer or not?
I am using the GNU GCC compiler and when I compile and run the following code it works but when I use any optimization like O1, O3, etc it does not work.
#include <iostream>
bool mul_overflows(int a,int b)
{
cout<<"checking overflow for"<<a<<" "<<b<<endl;
if(a==0 || b==0)
{
return false;
}
int result = a*b;
cout<<"result = "<<result<<endl;
cout<<"result/b = "<<(result/b)<<endl;
if(a==result/b)
return false;
return true;
}
int main()
{
if(mul_overflows(253955520,12)
cout<<"caught overflow!"<<endl;
}
Following is the output of code with default optimization -O0
checking overflow for 253955520 12
result = -1247501056
result/b = -103958421
caught overflow!
And when I use any other optimization it gives this output
checking overflow for253955520 12
result = -1247501056
result/b = 253955520
The overflow is not caught and we can clearly see that the result is negative and has overflowed, but still dividing the result by b gives a? What is causing this? Are there any compiler options that I am missing?