Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 409
Yash Catchem Avatar asked Apr 27 '18 18:04

Yash Catchem


3 Answers

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

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

like image 64
haccks Avatar answered Oct 19 '22 22:10

haccks


C89 allowed implementations to use any combination of rounding up and down for three of the four combinations of positive and negative operands (when both operands were positive, it mandated rounding down). At the time, most platforms performed division in a way that would make truncating for all combinations of operands more efficient than consistently using any other rounding mode for some combinations, and consequently C implementations for those platforms did likewise. This in turn lead to C99 mandating that particular behavior.

Ironically, the way many platforms now perform division (processing division by a constant as a multiply-and-shift operation), truncation is no longer the most efficient way of handling non-zero remainders, but the conventions which date back to a time when it was are now locked in stone.

like image 27
supercat Avatar answered Oct 19 '22 23:10

supercat


What is the behavior of C89 with respect to division of two negative numbers

The quotient will be 1 or 2.

int var;
var=-8/-5;

C89 allowed a division of 2 integers (with at least one negative) that had a non-zero remainder to the higher or lower integer result. The standard library provided div() to calculate the quotient and remainder consistently across compilers without this flexibility.

div_t     div( int x, int y );

This function had a specified "truncated towards zero" which is the behavior of / since C99. This allowed for portable, if sometimes slightly inefficient, C89 code.

like image 32
chux - Reinstate Monica Avatar answered Oct 19 '22 23:10

chux - Reinstate Monica