Search code examples
c++overflowinteger-overflowunderflow

Checking for underflow/overflow in C++?


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.


Solution

  • 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
    }