# Why are you getting different values ​​for integer division in C89?

For example, suppose you have these variables:

``````int i = 9;
int j = 7;
```

```

Depending on the implementation, the value `(-i)/j`

can be either `–1`

or `–2`

. How can you get these two different results?

+3

source to share

Surprisingly, the result is an implementation defined in C89:

ANSI draft § 3.3.5

When integers are divisible and division is imprecise , 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 of the operands is negative, the result of the operator / is the largest integer, lesser algebraic relation, or smallest integer greater than the algebraic quotient is implementation-defined

However, this was changed in C99

N1256 § 6.5.5 / 6

When integers are divisible, the result of the operator / is an algebraic factor with any fractional part discarded *

With a note:

* This is often referred to as "truncating to zero"

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

+9

source

In C89, the result of division `/`

can be truncated anyway for negative operands. (In C99, the result will be truncated to zero.)

The historical reason is explained in C99 Rationale:

### Rationale for an International Standard - Programming Languages ​​- C §6.5.5 Multiplicative operators

In C89, the division of integers with negative operands can round up or down according to implementation; the goal was to avoid running-time overhead in order to check for special cases and enforce certain behavior. However, in Fortran, the result will always be truncated to zero, and the overhead seems to be acceptable to the numerical programming community. Hence, C99 now requires similar behavior, which should make it easier to port your Fortran code to C.

+3

source

All Articles