2
votes

Asumming a=1

1+(-1) =0

but with 4 bit binary ,using 2's complement

0001+1111=10000 ~ 0000

Isn't signed integer overflow undefined behavior ?

Do we depend on undefined behavior for such trivial result or I am missing something .

from wikipedia: If the left two carry bits (the ones on the far left of the top row in these examples) are both 1s or both 0s, the result is valid; if the left two carry bits are "1 0" or "0 1", a sign overflow has occurred.

4
Why would this be any different than 8-bit, 16-bit, etc? If you add 000...01 to 111...11 you get 000...00.lurker
This may help as it discusses the carry bits and overflow: en.wikipedia.org/wiki/Two's_complement#Additionhatchet - done with SOverflow
When you add signed number with opposite signals, there will never be an overflow, what you are seeing is the carry number propagation to enable larger container to operate correctly.Amadeus
"EDIT : from wikipedia link" which link?Amadeus
When Wikipedia talks about the left two carry bits, it clearly specifies they are not the ones in the far left of the top row in your examples. Look at the Wikipedia page again for 11111 111 (carry)Mooing Duck

4 Answers

3
votes

Adding signed numbers with opposite signs never generate overflow. Indeed, hardware usually has two flag bits related to addition, i.e., overflow bit and carry bit.

Overflow bit is only set if the container is not large enough to represent the number correctly. For signed number the hardware set this bit after analyzing the sign bit of each operand and the sign of the results. If the signs of operands are differents, it will never set this bit. Otherwise, if the signals of operands are equals, it analyses the sign of result. If it is different from the operands, it set this flag, indicating that the result is in overflow.

In your example, the sign of each operand is different, so there no overflow, but this operation generate a carry bit if you want to use large container to keep operation correct.

2
votes

Signed integer overflow is undefined, but I fail to see how this would be an issue here, since you are adding two signed numbers and the result does fall within range.

For a 4 bit integer type, overflow would be adding 7+7, where the result should be 14 that does not fit in the range -2^3..2^3-1

0
votes

The underlying representation may internally use overflow to get the correct result, but that is irrelevant. The behavior is only undefined if the result of an operation exceeds the range of the type.

-1
votes

It is undefined behavior but I'm not sure I understand your question. Are you asking why it works in that example? Because those values are within range and the result is in range. Consider

-8 + -1

In 4 bit

1000 + 1111 -> 10111 -> 0111 -> 7. Here we no longer have the correct answer