core.checkedint

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Fri Jun 24 15:55:39 PDT 2016


To bring a different angle, the best front-end for arithmetic operations 
that may overflow is:

typeof(lhs + rhs) add(L, R)(const L lhs, const R rhs, ref bool overflow)
if (isIntegral!L && isIntegral!R);

The overflow bit is set if and only if the mathematical result is not 
the same as the concrete result. Interestingly, things like add(5u, -1) 
should succeed without overflow (returning 4u) even though the negative 
value is conceptually converted to a large positive number and the 
operation overflows. (I've implemented this behavior in the DbI checkedint.)

One point that escaped me initially is that sometimes there's no need 
for any checks, e.g. adding any two types smaller than int doesn't need 
to be checked.

I'm not sure whether this function belongs in core.checkedint, but 
that's the right front end design for the primitives in there.


Andrei



More information about the Digitalmars-d mailing list