Checking for underflow/overflow in C++?

Legend picture Legend · Mar 8, 2010 · Viewed 15.7k times · Source

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.

Answer

Stephen L picture Stephen L · Mar 8, 2010

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
}