The case for integer overflow checks?
Neia Neutuladh via Digitalmars-d
digitalmars-d at puremagic.com
Fri Sep 15 16:04:08 UTC 2017
On Friday, 15 September 2017 at 12:33:56 UTC, Adam D. Ruppe wrote:
> On Friday, 15 September 2017 at 12:04:27 UTC, Kagamin wrote:
>> Since width can't be negative, C programmer would use unsigned
>> integer for it
>
> That's often a big mistake. Lots of people do it... but you
> shouldn't, exactly because of the wraparound behavior.
Signed integers have the same issue, no? Using int32s:
2147483635 * 400000000 * 4 = 674836480
It's just that you're more likely to be able to detect it, since
a lot of inputs result in negative numbers.
One solution is to switch to the next larger integer size. That
works up to 32-bit numbers. When you hit 64-bit, you've got to
switch to BigInt.
Another solution is to check the overflow bit as appropriate. The
checkedint package automates that.
The last solution that I can think of, specific to this type of
thing, is to use the result to allocate a bounds-checked array,
where the allocation function yields the appropriately sized
array. You'll get an array bounds error that may be inscrutable.
More information about the Digitalmars-d
mailing list