🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #3009

Re: mathematical modulo operation

#3009
From: Mark Brader
Date: Sat, 12 Dec 1992 23:11
44 lines
2531 bytes
I've found the persistence of this thread surprising.  To my mind,
the answer to the original question

| Is this implementation of the modulo function guaranteed [to work?]
| int mod(int j,int N) {return((((j)%N) < 0) ? ((j) % N)+N : ((j) % N));}
 
is clearly Yes.  The counter-argument

> Strictly speaking, the implementation is free to define which of two
> allowed results is produced for % when the divisor is negative.  I don't
> know any implementation where the implementation definition might say that
> the result alternates from one invocation to the next, but it's not clear
> if the standard allows it.

seems entirely specious to me.  What section 3.3.5/6.3.5 actually says is
the following; I have added emphasis.

#  If either operand is negative, WHETHER THE RESULT of the / operator
#  IS the largest integer less than or equal to the algebraic quotient
#  OR the smallest integer greater than or equal to 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.

To me this clearly means that the implementation must define it as one
value or the other.  If it was intended that it could vary from one to
another from one instance of the operation to another, then there would
be no point in making it implementation-defined at all; the standard
might as well have said that it was unspecified, the way it does for
evaluation order.

By wording it as it does, the standard is, precisely, allowing for
functions such as the one mentioned above.

It's still a puzzle to me why, having provided the above definition,
they then proceeded to specify the library functions div() and ldiv()
as they did, but not provide functions that would provide the mathematical
modulo function, which I think is more useful.  But this is incidental.
-- 
Mark Brader			"Could you please continue the petty bickering?
SoftQuad Inc., Toronto		 I find it most intriguing."
utzoo!sq!msb, msb@sq.com		-- Data ("Haven", ST:TNG, Tracy Torme)

This article is in the public domain.
Technical Details
Message-ID: <1992Dec12.231115.26787@sq.sq.com>
Path: arc1-ca.pugleaf.net!sparky!uunet!uunet.ca!wildcan!sq!msb
References: <Byx9D9.5v7@jrd.dec.com> <1254@zogwarg.etl.army.mil> <Bz2nuL.130@jrd.dec.com>

Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c
Path: arc1-ca.pugleaf.net!sparky!uunet!uunet.ca!wildcan!sq!msb
From: msb@sq.sq.com (Mark Brader)
Subject: Re: mathematical modulo operation
Message-ID: <1992Dec12.231115.26787@sq.sq.com>
Organization: SoftQuad Inc., Toronto, Canada
References: <Byx9D9.5v7@jrd.dec.com> <1254@zogwarg.etl.army.mil> <Bz2nuL.130@jrd.dec.com>
Date: Sat, 12 Dec 92 23:11:15 GMT
Lines: 44