Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
–
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.
–
–
–
–
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.
–
–
–
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 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).
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;
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.