views:

444

answers:

4

Is there a general way to check for an overflow or an underflow of a given data type (uint32, int etc.)?

I am doing something like this:

uint32 a,b,c;
... //initialize a,b,c
if(b < c) {
   a -= (c - b)
}

When I print a after some iterations, it displays a large number like: 4294963846.

+6  A: 

To check for over/underflow in arithmetic check the result compared to the original values.

uint32 a,b;
//assign values
uint32 result = a + b;
if (result < a) {
    //Overflow
}

For your specific the check would be:

if (a > (c-b)) {
    //Underflow
}
Stephen L
Thanks. This seems to work fine for now...
Legend
+3  A: 

I guess if I wanted to do that I would make a class that simulates the data type, and do it manually (which would be slow I would imagine)

class MyInt
{
     int val;
     MyInt(const int&nval){ val = nval;} // cast from int
     operator int(){return val;} // cast to int

    // then just overload ALL the operators... putting your check in
};

//typedef int sint32;
typedef MyInt sint32;

it can be more tricky than that, you might have to wind up using a define instead of a typedef...

I did a similar thing with pointers to check where memory was being written out side of bounds. very slow but did find where memory was being corrupted

matt
Was looking for a simpler approach... But in any case, thanks for this..
Legend
A: 

4294963846 = -3450 in two's complement. Your subtraction is giving you a negative number. In this case, the easiest approach would be to simply switch to signed integers.

dan04
Sure I would've if I was writing my own code :) I am writing a module for a larger codebase so I don't really have the flexibility...
Legend
+1  A: 

In C# you can do this with checked:

uint32 a,b,c; 
... //initialize a,b,c 
try {
    checked {
        if(b < c) { 
           a -= (c - b) 
        }
    }
} catch (OverflowException e) {
// overflow happened
}
Gabe
-1: this isn't standard C++ (but will work in C#) and as such isn;t the general solution requested
Elemental
Sure enough. I don't know why I didn't notice it was C++. I supposed I should delete this answer, but I don't know how.
Gabe