As shown below, the code has a bug. When input a = -1, b = 1, one of the line has runtime error. Could you please help me understand how (a & b) becomes INT_MIN?
In my understanding, -1 is represented as 32-bit binary format 0xFFFFFFFF, and 1 is represented as 32-bit format 0x00000001, thus (-1 & 1) will become 0x00000001. And my python command also shows '0b1' as result. Why does it report the error of INT_MIN?
int getSum(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1;//BUG! left shift of negative value -2147483648
a = a ^ b;
b = carry;
}
return a;
}
Update: Is right shift for negative numbers well-defined? It seems ok to right shift negative numbers as long as it satisfies the requirements as quoted below.
From cppreference.com,
For unsigned a and for signed a with nonnegative values, the value of a >> b is the integer part of a/2b . For negative a, the value of a >> b is implementation-defined (in most implementations, this performs arithmetic right shift, so that the result remains negative).
In any case, if the value of the right operand is negative or is greater or equal to the number of bits in the promoted left operand, the behavior is undefined.
int
's range, therefore it's not an overflow – phuclva & b
is1
as you say, but you are in awhile
loop that updates the values ofa
andb
, the bug comes on a later iteration – M.M