Created on 2007-01-15.00:00:00 last changed 157 months ago
[Voted into the WP at the September, 2008 meeting as part of paper N2757.]
Proposed resolution (August, 2008):
Change 7.6.5 [expr.mul] paragraph 4 as follows:
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined
; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined. [Footnote: 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. —end footnote]
[Drafting note: see C99 6.5.5 paragraph 6.]
The current Standard leaves it implementation-defined whether integer division rounds the result toward 0 or toward negative infinity and thus whether the result of % may be negative. C99, apparently reflecting (nearly?) unanimous hardware practice, has adopted the rule that integer division rounds toward 0, thus requiring that the result of -1 % 5 be -1. Should the C++ Standard follow suit?
On a related note, does INT_MIN % -1 invoke undefined behavior? The % operator is defined in terms of the / operator, and INT_MIN / -1 overflows, which by Clause 7 [expr] paragraph 5 causes undefined behavior; however, that is not the “result” of the % operation, so it's not clear. The wording of 7.6.5 [expr.mul] paragraph 4 appears to allow % to cause undefined behavior only when the second operand is 0.
|2008-10-05 00:00:00||admin||set||messages: + msg1815|
|2008-10-05 00:00:00||admin||set||status: review -> cd1|
|2008-08-25 00:00:00||admin||set||messages: + msg1750|
|2008-08-25 00:00:00||admin||set||status: open -> review|