Computer Arithmetic
In C, what are the results of −7 / 2 and −7 >> 1 (with an arithmetic shift) for int?
- A−7 / 2 is −3, and −7 >> 1 is −4
- BBoth are −4
- C−7 / 2 is −4, and −7 >> 1 is −3
Show answer and explanation
Answer: A. −7 / 2 is −3, and −7 >> 1 is −4
C (since C99) defines integer division as truncating toward zero, so −3.5 becomes −3. An arithmetic right shift instead rounds toward negative infinity: shifting −7 (1111 1001) right by one gives 1111 1100 = −4. For negative numbers, shifting and dividing therefore disagree, so when compilers replace division by 2 with a shift they add correction instructions for negatives. For positive numbers the two agree.
- A. Correct. Division truncates toward zero; the shift rounds downward.
- B. Division truncates toward zero, giving −3.
- C. The pairing is reversed.