Disable implicit conversion

Jonathan M Davis jmdavisProg at gmx.com
Mon Mar 7 15:03:57 PST 2011


On Monday, March 07, 2011 12:10:07 spir wrote:
> On 03/07/2011 05:40 PM, Jesse Phillips wrote:
> > 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.
> 
> I agree. Then, why do we still have cast?

D is a systems language. It's supposed to let you do low level stuff like write  
kernel. Casts are required in such an environment, so it's not like we can't 
_not_ have them in the language, and in many cases, std.conv.to just casts 
anyway. So, while it might be best practice to prefer std.conv.to to casting, we 
still need casts in the language.

- Jonathan M Davis


More information about the Digitalmars-d mailing list