Does either ANSI C or ISO C specify what -5 % 10 should be?

C89, not totally (§3.3.5/6). It can be either -5 or 5, because -5 / 10 can return 0 or -1 (% is defined in terms of a linear equation involving /, * and +):

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.

C99, yes (§6.5.5/6), the result must be -5:

When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.88) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

88) This is often called “truncation toward zero”.


Similarly, in C++98 the result is implementation defined (§5.6/4), following C89’s definition, but mentions that the round-towards-zero rule is preferred,

… If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined74).

74) According to work underway toward the revision of ISO C, the preferred algorithm for integer division follows the rules defined in the ISO Fortran standard, ISO/IEC 1539:1991, in which the quotient is always rounded toward zero.

and indeed it becomes the standard rule in C++0x (§5.6/4):

… For integral operands the / operator yields the algebraic quotient with any fractional part discarded;82

82) This is often called truncation towards zero.

Leave a Comment