Which is better option to use for dividing an integer number by 2?

前端 未结 23 1695
甜味超标
甜味超标 2020-11-27 09:10

Which of the following techniques is the best option for dividing an integer by 2 and why?

Technique 1:

x = x >> 1;

Technique

23条回答
  •  [愿得一人]
    2020-11-27 09:36

    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 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

提交回复
热议问题