Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

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

I seem to remember that ANSI C didn't specify what value should be returned when either operand of a modulo operator is negative (just that it should be consistent). Did it get specified later, or was it always specified and I am remembering incorrectly?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...