Integer division rounding with negatives in C++

Viewed 23090

Suppose a and b are both of type int, and b is nonzero. Consider the result of performing a/b in the following cases:

  1. a and b are both nonnegative.
  2. a and b are both negative.
  3. Exactly one of them is negative.

In Case 1 the result is rounded down to the nearest integer. But what does the standard say about Cases 2 and 3? An old draft I found floating on the Internet indicates that it is implementation dependent (yes, even case 2) but the committee is leaning toward making it always 'round toward zero.' Does anyone know what the (latest) standard says? Please answer only based on the standard, not what makes sense, or what particular compilers do.

4 Answers

According to the May 2008 revision,

You're right:

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined75).

Note 75 says:

According to work underway toward the revision of ISO C, the preferred algorithm for integer division follows the rules defined in the ISO Fortran standard, ISO/IEC 1539:1991, in which the quotient is always rounded toward zero.

Chances are that C++ will lag C in this respect. As it stands, it's undefined but they have an eye towards changing it.

I work in the same department as Stroustrup and with a member of the committee. Things take AGES to get accomplished, and its endlessly political. If it seems silly, it probably is.

Just a comment. The current working draft for the C++ standard indeed corrects the "implementation-defined" issue and asks for truncation towards zero. Here is the committee's webpage, and here is the draft. The issue is at page 112.

Sometimes we need to take a step back, and look just at the mathematics of it:

Given int x, int y

if int i1 = x/y and int i2 = x%y

then y * i1 + i2 must be x

So this is not so much about the standard, but there is only one way this can possibly be. If any standards allows it to be any other way, then the standard is wrong, and that means the language is broken.

Related