[D1] modulo on neg integer

qwerty qw at er.ty
Thu Mar 18 05:44:35 PDT 2010


bearophile Wrote:

> qwerty:
> > If memory serves me right, module is undefined on negative integers.
> 
> I think it's defined in D (but it's defined badly).
Got url ? :)
> 
> 
> > int i = -2;
> > i%=10; // i=undefined?
> > What should I use instead to get i definitely equal to 7?
> 
> D outputs -2, Python outputs 8. It's not easy to find a language that outputs 7 there, maybe Malborge language?

8 yeah :(somehow I did overcompensated for the max being 9 for %10)

 i      = -3 -2 -1  0  1  2
 i%3 =  7  8  9  0  1  2

So I should be safe with 
i % M;
if(i<0) i = M + i;

> 
> > On a sidenote, where can I read about operation order/definitions?
> > Like i++, ++i and i%10 not changing i etc. 
> 
> D acts like C, here. Even when C does something badly. So you can surely find info about ++ and % in C.
I'd wish it was available here, as I don't really know C(++).



More information about the Digitalmars-d-learn mailing list