Title
Results of integer / and %
Status
cd1
Section
7.6.5 [expr.mul]
Submitter
Gabriel Dos Reis

Created on 2007-01-15.00:00:00 last changed 197 months ago

Messages

Date: 2008-09-15.00:00:00

[Voted into the WP at the September, 2008 meeting as part of paper N2757.]

Date: 2008-08-15.00:00:00

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]. For integral operands, the / operator yields the algebraic quotient with any fractional part discarded; [Footnote: This is often called “truncation towards zero.” —end footnote] if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.

[Drafting note: see C99 6.5.5 paragraph 6.]

Date: 2020-12-15.00:00:00

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.

History
Date User Action Args
2008-10-05 00:00:00adminsetmessages: + msg1815
2008-10-05 00:00:00adminsetstatus: review -> cd1
2008-08-25 00:00:00adminsetmessages: + msg1750
2008-08-25 00:00:00adminsetstatus: open -> review
2007-01-15 00:00:00admincreate