What does (a + b) >> 1 mean?

What does int c = (a+b) >>1 mean in C ++?

+4
source share
6 answers

Please note that there can be no meaningful explanation of what your code means until you explain what a and b .

Even if a and b are of built-in type, beware of incorrect answers, unconditionally asserting that the built-in right shift is equivalent to dividing by 2. Equivalence is only valid for non-negative values. The behavior of the >> operator for negative values ​​is determined by the implementation.

In other words, without additional information, the only thing that can be said is that the code calculates the “sum” a + b and “shifts” its right by 1 bit. I used quotes in the last sentence because in the case of overloaded operators + and >> there is no way to predict what they will do.

+12
source

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 aborts if a and b add a negative number, for example, if both are negative or an integer overflow occurs.

+18
source

It depends on type c, a and b. If it is int, then the above statement matches:

 c = (a+b)/2; 

>> means right shift one bit.

+6
source

This means adding A to B, then bit-shift the result one bit to the right. A bit-shift of a positive integer, as a rule, has the effect of multiplying or dividing by 2 ^ n, where n is the number of shifted bits. So this is roughly equivalent to (a + b) / 2 in integer math (which has no residues or fractional parts).

+2
source

This means that you add a and b and then shift the result one bit to the right.

This is the same as:

 int c = (a + b) / 2; 
+1
source

As mentioned above, this is an average function that uses the bit-shift operator in C ++ (with some potential traps in it) - the readability of this code is pretty poor due to this question. Help your fellow programmer and think about readability when writing code

+1
source

All Articles