Wingo
Wingo

Reputation: 15

How to check if a sum/multiplication/subtraction creates overflow?

So I am just trying to add two numbers together,

The first one is P1 = 2147483647 and the other is P2 = 1 This should overflow the type int so I wrote this to try to prevent the computer from doing the overflow

if((P1 + P2) > sizeof(int)){
    halt = 1; /*halt is just a flag*/
}

But the computer obviously still tries to do the sum to check it, giving me a runtime error before the message I wrote that simply says that I cannot add those two number together. How can I do that without occurring into the runtime error and just displaying my message?

I am also trying to do this for a subtraction and multiplication but the problem is the same.

EDIT : I need to do this for a project, I don't think I can use the library limits.h

Upvotes: 0

Views: 509

Answers (2)

Alain Merigot
Alain Merigot

Reputation: 11537

A classical bit trick to test overflow is to compute:

if( (~(p1^p2) & (p1^(p1+p2)) & (1ull<<(8*sizeof(p1)-1)) ){
  printf("overflow in the addition of p1 and p2") ;
}

The idea if that overflow can only occur when both numbers are of the same sign. In this case, it can proofed that overflow will produce a number with a sign different from one of the argument. That is what check the function.
So on the MSB (last part of the expression), check if signs of operands are identical (first part of the expression) and if sign of the result is different from sign of operand 1 (second part of the expression).

For a substraction, it is sufficient to remove the bit complement in the expresion.

Upvotes: 1

abelenky
abelenky

Reputation: 64682

#include <limits.h>
if (P2 > INT_MAX - P1) {
   printf("Overflow would occur\n");
}

Explanation:

INT_MAX - P1 is the biggest value you can add to P1 without overflow.
If P2 is bigger than that value, then it is too big, and overflow would occur.


If you need to check for an underflow as well, the math idea is the same:

if ( -P2 < P1 - INT_MIN) {
    printf("Underflow would occur\n");
} 

Explanation

(P1 - INT_MIN) is the biggest* value that could be subtracted from P1 without underflowing. If -P2 is even more negative than that, then underflow would occur on addition.

* Biggest by magnitude, not by value.

Upvotes: 2

Related Questions