0

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?

rici
  • 234,347
  • 28
  • 237
  • 341
shahryar
  • 83
  • 5
  • 2
    Signed integer overflow invokes *undefined behavior* [in the first place](https://stackoverflow.com/a/16188846/1322972). E.g. you're trying to put the lightening back in the bottle. – WhozCraig Feb 13 '21 at 04:07
  • 1
    `result/b` might be optimized to `a` – 김선달 Feb 13 '21 at 04:07
  • This has an answer https://stackoverflow.com/questions/199333/how-do-i-detect-unsigned-integer-multiply-overflow – doug Feb 13 '21 at 04:20

0 Answers0