modulus and array.length

"Jérôme M. Berger" jeberger at free.fr
Tue Nov 16 13:44:43 PST 2010


David Osborne wrote:
> Using arr.length
> -3 mod 3 = 1  <-- this should be 0
> -2 mod 3 = 2  <-- this should be 1
> -1 mod 3 = 0  <-- this should be 2
> 0 mod 3 = 0

	Like others have said, this is due to the fact that when one
operand is unsigned (here the length), then all operands get casted
to unsigned before the operation. Several people have asked that
array length be changed to a signed value because of that
(bearophile probably has a bug report for it ;) )

> Using x
> -3 mod 3 = 0
> -2 mod 3 = -2
> -1 mod 3 = -1
> 0 mod 3 = 0
> 
	This is consistent with the C behaviour. Note that according to the
C standard, the result of the modulus operation with negative
arguments is undefined. I don't remember if Walter has specified the
expected behaviour for D or if he left it undefined...

	Note that from a strictly mathematical point of view, this result
is valid: for all x and all n, x-(x%n) is a multiple of n.

		Jerome
-- 
mailto:jeberger at free.fr
http://jeberger.free.fr
Jabber: jeberger at jabber.fr

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: OpenPGP digital signature
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20101116/4f5dc1c3/attachment.pgp>


More information about the Digitalmars-d mailing list