Disable implicit conversion

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Mon Mar 7 03:30:14 PST 2011


On Mon, 07 Mar 2011 10:33:28 +0000, 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

DMD is simply trying to protect you from what is otherwise a common bug.  
As a general rule, the result of an integer subtraction should be stored 
in a signed integer, since the result may be negative.

If you are 100% sure that u2 >= u1, or if integer wraparound is what 
you're after, just use a cast:

  auto result = cast(ubyte)(u2 - u1);

-Lars


More information about the Digitalmars-d mailing list