Overflow-safe use of unsigned integral types

luka8088 luka8088 at owave.net
Sun Nov 10 23:52:35 PST 2013


On 10.11.2013. 12:10, Joseph Rushton Wakeling wrote:
> 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...:-)

Just for reference:
http://forum.dlang.org/thread/kn3f9v$25pd$1@digitalmars.com



More information about the Digitalmars-d-learn mailing list