Implicit integer casting

Simen Kjærås simen.kjaras at gmail.com
Sun Mar 18 12:55:24 PDT 2012


On Sun, 18 Mar 2012 20:30:15 +0100, Manu <turkeyman at gmail.com> wrote:

> On 18 March 2012 21:15, Tove <tove at fransson.se> wrote:
>
>> On Sunday, 18 March 2012 at 19:08:54 UTC, Manu wrote:
>>
>>> So D is really finicky with integer casts. Basically everything that  
>>> might
>>> produce a loss of data warning in C is an outright compile error.
>>> This results in a lot of explicit casting.
>>>
>>> Now I don't take issue with this, actually I think it's awesome, but I
>>> think there's one very important usability feature missing from the
>>> compiler with such strict casting rules...
>>> Does the compiler currently track the range of a value, if it is known?
>>> And
>>> if it is known, can the compiler stop complaining about down casts and
>>> perform the cast silently when it knows the range of values is safe.
>>>
>>> int x = 123456;
>>> x &= 0xFF; // x is now in range 0..255; now fits in a ubyte
>>> ubyte y = x; // assign silently, cast can safely be implicit
>>>
>>> I have about 200 lines of code that would be so much more readable if  
>>> this
>>> were supported.
>>> I'm finding that in this code I'm writing, casts are taking up more  
>>> space
>>> on many lines than the actual term being assigned. They are really  
>>> getting
>>> in the way and obscuring the readability.
>>> Not only masks, comparisons are also often used of limit the range of
>>> values. Add D's contracts, there is good chance the compiler will have
>>> fairly rich information about the range of integers, and it should
>>> consider
>>> that while performing casts.
>>>
>>
>> Walter even wrote an article about it:
>> http://drdobbs.com/blogs/**tools/229300211<http://drdobbs.com/blogs/tools/229300211>
>
>
> Interesting. This article claims: Can we do better? Yes, with "Value  
> Range
> Propagation", a historically obscure compiler optimization that became a
> handy feature in the D programming language.
>
> But it doesn't seem to work. Am I just doing something wrong?

It only works within one expression. This works:

   int n = foo();
   byte b = n & 0xFF;

This does not:

   int n = foo() & 0xFF;
   byte b = n;


More information about the Digitalmars-d mailing list