Zxcv Mnb
Zxcv Mnb

Reputation: 743

overflow during operation a+(-a)

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.

Upvotes: 2

Views: 244

Answers (4)

sedavidw
sedavidw

Reputation: 11741

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

Upvotes: -1

Amadeus
Amadeus

Reputation: 10665

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.

Upvotes: 3

David Brown
David Brown

Reputation: 13526

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.

Upvotes: 0

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

Upvotes: 2

Related Questions