Which of the following techniques is the best option for dividing an integer by 2 and why?
Technique 1:
x = x >> 1;
Technique
I agree with other answers that you should favor x / 2
because its intent is clearer, and the compiler should optimize it for you.
However, another reason for preferring x / 2
over x >> 1
is that the behavior of >>
is implementation-dependent if x
is a signed int
and is negative.
From section 6.5.7, bullet 5 of the ISO C99 standard:
The result of
E1 >> E2
isE1
right-shiftedE2
bit positions. IfE1
has an unsigned type or ifE1
has a signed type and a nonnegative value, the value of the result is the integral part of the quotient ofE1
/ 2E2
. IfE1
has a signed type and a negative value, the resulting value is implementation-defined.