Overflow-safe use of unsigned integral types
Joseph Rushton Wakeling
joseph.wakeling at webdrake.net
Sun Nov 10 03:10:23 PST 2013
One of the challenges when working with unsigned types is that automatic
wraparound and implicit conversion can combine to unpleasant effect.
Consider e.g.:
void foo(ulong n)
{
writeln(n);
}
void main()
{
foo(-3);
}
... which will output: 18446744073709551613 (or, ulong.max + 1 - 3).
Is there a recommended way to handle this kind of potential wraparound where it
is absolutely unacceptable? I've considered the following trick:
void bar(T : ulong)(T n)
{
static if (isSigned!T)
{
enforce(n >= 0); // or assert, depending on your priorities
}
writeln(n);
}
... but it would be nice if there was some kind of syntax sugar in place that
would avoid such a verbose solution.
I know that there have been requests for runtime overflow detection that is on
by default (bearophile?), but it could be good to have some simple way to
indicate "really, no overflow" even where by default it's not provided.
(Motivation: suppose that you have some kind of function that takes a size_t and
uses that to determine an allocation. If a negative number gets passed by
accident, the function will thus try to allocate 2^64 - n elements, and your
computer will have a very happy time...:-)
More information about the Digitalmars-d-learn
mailing list