Anders Lind Anders Lind - 3 months ago 14
C++ Question

How to catch integer overflow in C++?

I have a

sum()
function.
I need to catch all overflow.

I searched website but didn't find a good way to do so.

So...any thoughts?

Answer

If you add two numbers with the same sign, and you get a number of the opposite sign then you had an overflow. I don't know C++, but I know C code works in C++, you might want to make this more C++'ish though. This is C code to detect an overflow:

int sum(int a, int b){
    char sign =  a > 0 && b > 0 ? 1 : a < 0 && b < 0 ? -1 : 0;
    int sum = a+b;
    if (sign && sign == 1 && sum < 0 || sign == -1 && sum > 0){
        // Overflow occurred!
    }
    return sum;
}