[D1] modulo on neg integer

qwerty qw at er.ty
Thu Mar 18 05:54:12 PDT 2010


Don Wrote:

> qwerty wrote:
> > If memory serves me right, module is undefined on negative integers.
> > int i = -2;
> > i%=10; // i=undefined?
> 
> It's not undefined.  x%y always has the sign of x, so i will be -2.
> 
> This always holds:
> x == y * (x/y) + (x%y);
> And since D uses truncated division, the result follows.
> This behaviour is inherited from C99.
Ok, that seems sensible.
Yay,found the spec (mul expressions ?:):
"For integral operands of the / and % operators, the quotient rounds towards zero and the remainder has the same sign as the dividend. If the divisor is zero, an Exception is thrown. "
Personally I find your explanation a lot more clear :)

> 
> > What should I use instead to get i definitely equal to 7? 
> 
> You mean 8?
Yeah :(

> 
> i %= 10;
> if (i<0) i += 10;
> 
> > 
> > On a sidenote, where can I read about operation order/definitions?
> > Like i++, ++i and i%10 not changing i etc. 
> 



More information about the Digitalmars-d-learn mailing list