What is the behavior of C89 with respect to integer division of two negative numbers: round up, round down or not defined?

  • A+

For Example,

If I write

int var; var=-8/-5; 

As per operator precedence, -8/-5 would be equivalent to ((-8)/(-5)). But will it be possible for C89 to give two values like for the case of -8/5 it can give -1 or -2. or It will treat it as the division of two positive integers?

Question is in with reference to the book by K.N.King (C Programming A modern Approach)

C89 has rule that if either operand is negative then the result of a division can be rounded either up or down.

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, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

For example in case of -8/5; output of this could be -1 ((-8)/5) or -2 (-(8/5)).
In C99 it is guaranteed to be truncated towards 0.

In your case both the operands are -ve and output will be a +ve number (either 1 or 2 in this case).


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: