Link to home
Start Free TrialLog in
Avatar of Shrif
Shrif

asked on

Checking Overflow/Underflow on math

How does one check on overflow/underflow for the following C++ types: long, short, float, double, for add, subtract, multiply, divide.  Example:      long L;      L = 2147483647;
      L++;      // Check flag to see if it overflowed.Using assembly language, I can easily accomplish this under Intel/Win32 via:      seto al      mov fOverflow, alAnd for floating point, I can use _clearfp( ).  However, this is Microsoft compiler and Intel CPU specific.  How does one do this in plain C++??Is there a way?More sample code:      long L;
      L = 2147483647;
      L++
----
      short I;
      I = 32767;
      I++;
----
      double d;
      d = 1.7976931348623158e+308;
      d = d * d;
----
      float f;
      f = 16777216.000000;
      f++;
Avatar of chensu
chensu
Flag of Canada image

There is a Microsoft extension (Structured Exception Handling) in Visaul C++ to do it.

__try
{
...
}
__except( GetExceptionCode() == STATUS_INTEGER_OVERFLOW )
{
}

You can get more information by seeing the documentation that comes with Visual C++:
Visaul C++ Books/C/C++/Programming Techniques/Structured Exception Handling/.

Avatar of Shrif
Shrif

ASKER

I was very clear in stating in my question that I am seeking a non-platform specific answer.  I cannot rely on assembly language, or Visual C++.In addition, so that it is clear, I need the solution to also work for the largest possible type as well.  I say this because an obvious way to check for overflow on an integer is to perform the same operation with a larget size, a long, and compare the results.  This technique will fail for the largest size, double, which also needs to be handled.
There is an extension to ANSI C that provides for signal (SIGFPE), but it's not guarantted to be implemented by every compiler, and the handling of errno is not standardized either.  Anyway, it would cause a jump to your handler and that's not good for C++.

I would recommend an explicit check as follows:

Check = L = 2147483647;
L++;
if (Check != --L) //then overflow


Avatar of Shrif

ASKER

The proposed solution does not work.  If you add 1 to the value, you may overflow -- that's true, but that doesn't mean that subtracting from the result will not return you back to where you started.  It will.  Sorry.
ASKER CERTIFIED SOLUTION
Avatar of icd
icd

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial