Which of the following techniques is the best option for dividing an integer by 2 and why?
Technique 1:
x = x >> 1;
Technique
The answer to this will depend on the environment you're working under.
x /= 2
into x >>= 1
, the presence of a division symbol will raise more eyebrows in that environment than using a shift to effect a division.x >>= 1
with a comment explaining its reasoning is probably best just for clarity of purpose.x /= 2
. Better to save the next programmer who happens to look at your code the 10 second double-take on your shift operation than to needlessly prove you knew the shift was more efficient sans compiler optimization.All these assume unsigned integers. The simple shift is probably not what you want for signed. Also, DanielH brings up a good point about using x *= 0.5
for certain languages like ActionScript.