Implicit integer casting

James Miller james at aatch.net
Sun Mar 18 14:12:25 PDT 2012


On 19 March 2012 08:53, Andrej Mitrovic <andrej.mitrovich at gmail.com> wrote:
> Another classic which fails to compile is:
>
> import std.random;
> ubyte c = uniform(0, 256);
>
> In the call uniform returns a number anywhere from 0 to and including
> 255, which can fit perfectly in a ubyte. But I have to use a cast
> (which is error-prone if I change the right interval), or use a
> to!ubyte call (which is verbose). Granted for simple-purpose random
> number generation a cast might be safe..

Another thing I have noticed, is that that compared to a cast,
to!<type> is incredibly slow. Most of the time it doesn't matter, but
I was doing some work with noise generation, and found that casting
the floats to integers was an order of magnitude faster than using
to!int. Now I understand that this is about auto-casting, but I
thought I'd add the knowledge that to!<type> is slow, since it does
runtime checks on things like range, though I know that it cannot be
outside certain ranges.

Not that to!<type> is actually slow in the general case, but the
difference is significant when doing on the order of 10^6 casts.

--
James Miller


More information about the Digitalmars-d mailing list