What does int c = (a+b) >>1
mean in C++?
It returns the average of a
and b
, rounded down. So, if a
is 5 and b
is 8, then the result is 6.
ETA: This method is busted if a
and b
add up to a negative number, like if both are negative, or if integer overflow occurs.
That depends on the type of c, a and b. If it's int then the above statement is the same as:
c = (a+b)/2;
>>
means shift right one bit.
It means that you add a
and b
, then shift the result one bit to the right.
It's the same as:
int c = (a + b) / 2;
It means to add A to B, then bit-shift the result by one bit to the right. Bit-shifting a positive integer generally has the effect of multiplying or dividing by 2^n where n is the number of bits being shifted. So, this is roughly equivalent to (a+b)/2 in integer math (which has no remainders or fractional parts).
Note, that there can't be any meaningful explanation of what your code means until you explain what a
and b
are.
Even if a
and b
are of built-in type, beware of the incorrect answers unconditionally claiming that built-in right shift is equivalent to division by 2. The equivalence only holds for non-negative values. The behavior of the >>
operator for negative values is implementation-defined.
In other words, without extra information, the only thing that can be said is that the code calculates the "sum" a + b
and "shifts" it right by 1 bit. I used quotes in the last sentence because in case of overloaded operators +
and >>
there's no way to predict what they are doing.
As mentioned above, it's an average function utilizing the bit-shift operator in c++ (with some potential pitfalls in it) - by the existence of this question, the readability of this code is quite bad. Do your fellow programmer a favor and think about readability when you write code