0

I have to add numbers with this script:

for(i=1; i<1000 ;i++)
sum=sum+i;

it will overflow at 32768 and after that it goes to -32768 because it cant exceed the 16 bit limit.

i want to count the overflows with an int c.

Thanks

Sadique
  • 22,572
  • 7
  • 65
  • 91

1 Answers1

1

You can check if sum > sum + i

jhnesk
  • 29
  • 3
  • 1
    This only works for unsigned types. For signed types the result of overflow is undefined. Some compilers use that knowledge to always optimize `x + y > x` to true when y is known to be positive. http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html#signed_overflow – Art Sep 27 '13 at 13:49
  • That makes sense. Maybe its better to check `INT_MAX - sum < i`. This only works under the conditions that both i and sum is positive. – jhnesk Sep 27 '13 at 15:40