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.
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 quotienta/b
is representable, the expression(a/b)*b + a%b
shall equala
.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With