Dividing a negative integer by 2 is not the same as shifting it to the right by 1.For example
-7 / 2 = -3With shifts:
11111001b >> 1 = 11111100b which is -4Thus the compiler has to take care of the case when the integer is negative
What are cdq and sub doing? Are they necessary?
cdq performs the following EDX:EAX ← sign-extend of EAX.
Thus if the value in EAX is negative, EDX will get 0xFFFFFFFF (which is -1), otherwise it will be 0 (due to the sign extension of EAX).
sub eax, edx ; will either result in 'eax - 0' (if EAX is positive) or ; 'eax - (-1)' (if EAX is negative)Which in case of the above example will normalize the -7 to -7 - (-1) = -6 and then -6 >> 1 = -3.