Numeric limits tracking

Marco Leise Marco.Leise at gmx.de
Wed May 15 22:34:18 PDT 2013


Am Mon, 13 May 2013 10:00:40 +1000
schrieb Manu <turkeyman at gmail.com>:

> So, here's an issue that constantly drives me nuts, and an elegant solution
> seems so do-able.
> 
> void func(int x)
> {
>   x &= 0xFFFF;
>   short s = x; // Error! (but we know x is 0 .. 65535)
> 
>   if(x < 256)
>   {
>     byte b = x; // Error! (we also know x is 0 .. 255)
>   }
> }

Yes, I came across that one every so often myself. But as
David pointed out, such a feature would have to make it into
the D specification and implemented in all D compilers.
In any case I wouldn't call a half-baked "I will solve the
halting problem" flow-analysis elegant. :p

Let's think different. You could write
    short s = x & 0xFFFF;
on your first line, as you may already know DMD does this bit
of range analysis (same for modulo).

Also what was your intention? func() practically takes a short
parameter. Maybe it's signature should be
    void func(short x) {...}
If that's a problem on the calling site, maybe that can be
fixed?

bearophile's suggestion sounds like something that's pretty
solid and naturally extends the likes of "short s = x & 0xFFF;"
So if your "int x" was immutable it would really be trivial to
have your "if" change the range of immutable x during that
scope and have the assignment only fail because x may be
-1000. ;)

-- 
Marco



More information about the Digitalmars-d mailing list