Disable implicit conversion

Jesse Phillips jessekphillips+D at gmail.com
Mon Mar 7 08:40:26 PST 2011


KennyTM~ Wrote:

> On Mar 7, 11 18:33, Eugene wrote:
> > Hi!
> >
> > What I want to do is pretty simple.  I need to subtract a ubyte from a
> > ubyte and store the result in a ubyte.  The problem is that DMD
> > implicitly wants to convert the ubytes into an integer, so it fails
> > when attempting to store the result into a ubyte.  (Int cannot be
> > converted to ubyte?)
> > The error message I get:
> >
> > src\test.d(26): Error: cannot implicitly convert expression
> > (cast(int)u2 - cast(int)u1) of type int to ubyte
> 
> ubyte u3 = (u2 - u1) & 0xff;
> //                ^^^^^^
> //                   make sure the result fall in ubyte's value range

I recommend against this for a number of reasons.

For one this removes an explicit cast which makes it harder to find for review (one of the reasons for cast() instead of ().

Not only that but the operation isn't any safer than a cast, if overflow didn't matter and you just need it to fit then this would be good.

Lastly overflow does matter and if it happens the code will continue to silently work. I recommend using std.conv.to because it will throw an exception if an overflow were to happen.


More information about the Digitalmars-d mailing list