Signed Unit in C

I read the section on C portability in Andrew Cowang's C Traps and Pitfalls book.

On an integer divison

 q = a/b; r = a%b; 

If a is a negative number, then, apparently, the reminder r can be a negative or positive number satisfying the property

 q * b + r == a 

Normally, I would expect r to be negative if dividend a is negative. And this is what I see in intel machine with gcc. I'm just wondering, have you ever seen a car that will return a positive reminder when the dividend is a negative number?

+6
source share
1 answer

C99 formalized the remainder as bearing the same sign as the dividend. Up to C99 (C89 and K & R) this could go anyway, as both results are in line with the technical requirements. There are indeed compilers out there that do not conform to the C99 specifications in this matter, although I don't know anyone from my head.

In particular, section 6.5.5 (Multiplicative Operators) states:

¶5 The result of the operator / is the division factor of the first operand of the second; the result of the% operator is the remainder. In both operations, if the value of the second operand is 0, the behavior is undefined.

¶6 When the integers are divisible, the result of the operator / is an algebraic relation with any fractional part discarded. 87) If the factor a/b is representable, the expression (a/b)*b + a%b must be equal to a .

87) This is often called "truncation to zero."

With this new definition, the remainder is basically defined as what you expect mathematically from it.

EDIT

To ask a question in the comments, the C99 specification also indicates (note 240) that if the remainder is zero, then on systems where zero is not signed, the sign of r will be the same as the sign of the divisor, x.

'' When y ≠ 0, the remainder r = x REM y is determined independently of rounding by the mathematical relation r = x - ny, where n is the integer closest to the exact value x / y; when | n - x / y | = 1/2, then n is even. Thus, the remainder is always accurate. If r = 0, its sign must correspond to the value of x. This definition applies to all implementations.

+8
source

Source: https://habr.com/ru/post/912463/


All Articles