Overflow-safe use of unsigned integral types

mike james foo at bar.com
Sun Nov 10 04:19:17 PST 2013


On Sunday, 10 November 2013 at 12:05:45 UTC, 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...:-)

When writing software for embedded micros you can always check an 
overflow flag - is the no such mechanism on PC software?


-=mike=-


More information about the Digitalmars-d-learn mailing list