Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you get different values for integer division in C89?

Tags:

c

c89

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?

like image 976
Luis Averhoff Avatar asked Dec 11 '22 23:12

Luis Averhoff


1 Answers

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).

like image 95
Ryan Haining Avatar answered Dec 13 '22 12:12

Ryan Haining