Integer division in C

Integer division in modern C always rounds towards zero.
For example:

9/2 = 4
-9/2 = -4 (not -5)

This was was not always so. In early C versions and in the C89 standard, positive integer division rounded to zero, but result of negative integer division was implementation dependent!

From ยง3.3.5 Multiplicative operators of the C89 standard:

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

The same appears in the first edition of The C Programming Language book by Kernighan and Ritchie.

This implementation-defined behavior was fixed by the C99 standard which defined that integer division always rounds towards zero.

From ยง6.5.5 Multiplicative operators of the C99 standard:

When integers are divided, the result of the / operator is the algebraic
quotient with any fractional part discarded.

Thanks to Arch for pointing this out.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.