May 16, 2013
Am Mon, 13 May 2013 10:00:40 +1000
schrieb Manu <turkeyman@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

May 16, 2013
On Thu, 16 May 2013 07:34:18 +0200, Marco Leise <Marco.Leise@gmx.de> wrote:

> Am Mon, 13 May 2013 10:00:40 +1000
> schrieb Manu <turkeyman@gmail.com>:
>
>> 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)
>>   }
>> }
[snip]
> 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?

I believe the intention was to show an issue with the language, not to make a
function that assigns to a short and a byte only to throw them away.

Perhaps he needed to do some intermediate calculations at higher precision,
perhaps he needs it to be an int for interfacing with a C function, etc.

-- 
Simen
1 2
Next ›   Last »