4

For example, suppose you have these variables:

int i = 9;
int j = 7;

Depending on the implementation, the value of, (-i)/j, could be either –1 or –2. How is it possible to get these two different results?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Luis Averhoff
  • 385
  • 6
  • 22

2 Answers2

9

Surprisingly the result is implementation defined in C89:

ANSI draft § 3.3.5

When integers are divided and the division is inexact, if both operands are positive the result of the / operator is the largest integer less than the algebraic quotient and the result of the % operator is positive. If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined

However this was changed in C99

N1256 § 6.5.5/6

When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded*

With a footnote:

* This is often called "truncation toward zero"

To clarify, "implementation defined" means the implementation must decide which one, it doesn't mean sometimes you'll get one thing and sometimes you'll get another (unless the implementation defined it to do something really strange like that, I guess).

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
4

In C89, the result of division / can be truncated either way for negative operands. (In C99, the result will be truncated toward zero.)

The historical reason is explained in C99 Rationale:

Rationale for International Standard — Programming Languages — C §6.5.5 Multiplicative operators

In C89, division of integers involving negative operands could round upward or downward in an implementation-defined manner; the intent was to avoid incurring overhead in run-time code to check for special cases and enforce specific behavior. In Fortran, however, the result will always truncate toward zero, and the overhead seems to be acceptable to the numeric programming community. Therefore, C99 now requires similar behavior, which should facilitate porting of code from Fortran to C.

Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294