Archive for May, 2011
C89 and C++98 say the result of an integer division where the divisor and/or dividend is negative is implementation defined. This reflects that early hardware implemented integer divisions differently.
According to C89/C++98, we may have either
(-3)/2 == -1 (round toward zero) or
(-3)/2 == -2 (round toward negative infinity).
It appears round toward zero has become the overwhelming de facto standard now, adopted by both hardware and software vendors. Now both C and C++ explicitly require round toward zero in their new standards (C99 and C++2011*).
Division of negative integers has always been a complicated problem. Fortran mandated the same round-toward-zero mode much earlier than C/C++; so did Java. Python, on the other hand, has required round toward -∞ (i.e.
(-3)//2 == -2) from its beginning. Everybody, nevertheless, agrees that
a/b*b + a%b == a should always hold.
* C++0x has yet to be officially approved. Hopefully it will be approved within this year and known as C++2011. I’m using this name prematurely.