Should % ever "overflow"?

Timon Gehr via Digitalmars-d digitalmars-d at puremagic.com
Fri Jun 24 14:27:52 PDT 2016


On 24.06.2016 22:33, Andrei Alexandrescu wrote:
> In a checked environment, division may "overflow", e.g. -6 / 2u must be
> typed as uint but is not representable properly one.
>
> How about remainder? I suppose one can make the argument that remainder
> should never overflow (save for rhs == 0),

Well, actually, lhs % 0 should be equal to lhs... :-)

Division by the trivial ideal {0} leaves the ring structure intact, so 
modular arithmetic modulo 0 is just regular arithmetic.

(But of course, the hardware traps, so it makes sense to just copy that 
behavior.)

> because it could be defined
> with either a positive or negative denominator (which is not part of the
> result).
>
> What's the most reasonable behavior?
>...

It should be consistent with whatever '/' does: a/b*b + a%b == a.

If this cannot be satisfied, it should 'overflow'. (As deadalnix also 
suggested.)



More information about the Digitalmars-d mailing list