checkedint call removal

bearophile via Digitalmars-d digitalmars-d at puremagic.com
Mon Jul 28 02:46:33 PDT 2014


Ola Fosheim Grøstad:

> IMO muls should yield 2N bits of output for N bits input, then 
> the compiler should do strength reduction.
>
> Adds should be done on N+1 bits types, using 33 bit output for 
> 32 bits input, then strength reduce it to >=32 bit output if 
> both operands are 31 bits or less?

I copy here a comment I've written here:
https://github.com/D-Programming-Language/phobos/pull/1866#issuecomment-50216839

A core.checkedint function like muls() accepts two ints or two 
longs. What if you have a uint and int? An example:

void main() {
     import std.stdio, core.checkedint;
     int x = -1;
     uint y = 3_000_000_000;
     writeln(x, " ", y);
     writeln(x * y);
     bool overflow = false;
     immutable r1 = muls(x, y, overflow);
     writeln(r1, " ", overflow);
     overflow = false;
     immutable r2 = mulu(x, y, overflow);
     writeln(r2, " ", overflow);
}

It outputs:

-1 3000000000
1294967296
1294967296 false
1294967296 true

Here the overflow boolean from the muls() is false, but the 
result is wrong (it's -3_000_000_000 that is not representable by 
both ints and uints).

Bye,
bearophile


More information about the Digitalmars-d mailing list