Why there is too many uneccessary casts?

bearophile bearophileHUGS at lycos.com
Tue Jun 11 04:17:17 PDT 2013


Temtaime:

> ubyte k = 10;
> ubyte c = k + 1;
>
> This code fails to compile because of: Error: cannot implicitly 
> convert expression (cast(int)k + 1) of type int to ubyte
>
> Why? It's pain in the ass, i think. My code contains only casts 
> then.

I agree that sometimes that's a pain.
Currently D performs a range analysis only inside one expression, 
and not across different ones.

One way to avoid the cast is to perform a masking:

void main() {
     immutable ubyte UB = ubyte.max;
     ubyte k = 10;
     ubyte c = (k + 1) & UB;
}



The solution is to improve D.
Beside fixing this bug:
http://d.puremagic.com/issues/show_bug.cgi?id=9107

A first step is to keep the range value for immutable variables, 
but this is not enough to solve your problem because your k is 
mutable:
http://d.puremagic.com/issues/show_bug.cgi?id=10018

Your case is very simple. It's just a sequence of instructions, 
with no gotos, no jumps, no control instructions, no function 
calls. Introducing some simple conservative rules for such simple 
situation is possible. But the advantage of the current situation 
is that it make usually easy to know where to put a cast and 
where it's not needed. The more complex the rules become, the 
harder is to know where the casts are not needed.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list