modulus and array.length

Jens Mueller jens.k.mueller at gmx.de
Tue Nov 16 09:45:36 PST 2010


Hi,

> I've noticed that the modulus operator acts differently when the divisor is
> the length of an array and the dividend is negative.
> For instance, this code:
> 
> import std.stdio;
> const int x = 4;
> void main(){
>     int[x] arr = [0, 1, 2, 3];
> 
>     writeln("Using arr.length");
>     for(int i = -3; i <= 0; i++){
>         writefln("%d mod %d = %d", i, arr.length, i % arr.length);
>     }
>     writeln("Using x");
>     for(int i = -3; i <= 0; i++){
>         writefln("%d mod %d = %d", i, x, i % x);
>     }
> }
> 
> Produces this output:
> 
> Using arr.length
> -3 mod 4 = 1
> -2 mod 4 = 2
> -1 mod 4 = 3
> 0 mod 4 = 0
> Using x
> -3 mod 4 = -3
> -2 mod 4 = -2
> -1 mod 4 = -1
> 0 mod 4 = 0
>
>  Which is a useful (but undocumented?) feature that lets you loop through
> arrays backwards.

arr.length is type size_t.
size_t length = 4;

writeln("Using size_t");
for(int i = -3; i <= 0; i++){
	writefln("%d mod %d = %d", i, length, i % length);
}

So it's due to the size_t. Because it's unsigned.

> However, when the length of the array is odd...
> const int x = 3;
> ...
> int[x] arr = [0, 1, 2];
> It looks like this:
> 
> 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
> Using x
> -3 mod 3 = 0
> -2 mod 3 = -2
> -1 mod 3 = -1
> 0 mod 3 = 0
> 
> Does anyone know of a reason for this? It doesn't seem like a bug, but I
> don't know why it would do something like that.

Here I have no idea.

Jens


More information about the Digitalmars-d mailing list