Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two's complement addition overflow in C

Tags:

c

debugging

I saw a buggy code in C which was used to check whether addition results in overflow or not. It works fine with char, but gives incorrect answer when arguments are int and I couldn't figure why .
Here's the code with short arguments.

short add_ok( short x, short y ){
    short sum = x+y;
    return (sum-x==y) && (sum-y==x);
}

This version works fine, problem arise when you change arguments to int ( you can check it with INT_MAX )
Can you see what's wrong in here ?

like image 961
Rsh Avatar asked Jul 12 '12 20:07

Rsh


People also ask

What is overflow in 2's complement addition?

Overflow Rule for additionIf 2 Two's Complement numbers are added, and they both have the same sign (both positive or both negative), then overflow occurs if and only if the result has the opposite sign. Overflow never occurs when adding operands with different signs.

How do you determine overflow in two's complement addition?

Two's Complement Overflow Rules. The rules for detecting overflow in a two's complement sum are simple: If the sum of two positive numbers yields a negative result, the sum has overflowed. If the sum of two negative numbers yields a positive result, the sum has overflowed.

How will you identify the overflow condition after binary addition?

Overflow Detection – So overflow can be detected by checking Most Significant Bit(MSB) of two operands and answer. But Instead of using 3-bit Comparator Overflow can also be detected using 2 Bit Comparator just by checking Carry-in(C-in) and Carry-Out(C-out) from MSB's. Consider N-Bit Addition of 2's Complement number.

What is complement overflow?

Overflow occurs when the number that you trying to represent is out of the range of numbers that can be represented. In your example you are using 4-bits two's complement, that means you can represent any number in the range -8 ( 1000 ) up to +7 ( 0111 ).


1 Answers

Because in 2s complement, the integers can be arranged into a circle (in the sense of modulo arithmetic). Adding y and then subtracting y always gets you back where you started (undefined behaviour notwithstanding).

like image 86
Oliver Charlesworth Avatar answered Sep 24 '22 14:09

Oliver Charlesworth