How to check if an integer addition will overflow (C)

For a recent Uni project, I had to check user input for erroneous inputs. Since the program was adding together two integers, I needed to determine whether the resulting integer didn’t overflow – that is to say that the number is outside the range that can be represented by the computer. After some thinking, I settled on the following:

int will_overflow(int a, int b) {
        if (   (a > 0 && a > MAX_INT - b) 
            || (a < 0 && a < MAX_INT - b))
                return 1;
        return 0;

The first check is for positive numbers, and the second is for negative, so this is a catch-all solution. The MAX_INT was defined as 2147483647 using the #define compiler statement. It works because it checks whether the first number is greater than the largest representable number minus the second number.

Leave a Reply

Your email address will not be published. Required fields are marked *