Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Integer division in C

📅 2019-Mar-06 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp ⬩ 📚 Archive

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.


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧