size_t index=-1;

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Mar 16 18:57:16 PDT 2016


On Wednesday, March 16, 2016 22:37:40 Mathias Lang via Digitalmars-d-learn 
wrote:
> On Wednesday, 16 March 2016 at 21:49:05 UTC, Steven Schveighoffer
>
> wrote:
> > No, please don't. Assigning a signed value to an unsigned (and
> > vice versa) is very useful, and there is no good reason to
> > break this.
> >
> > -Steve
>
> I'm not talking about removing it completely. The implicit
> conversion should only happen when it's safe:
>
> ```
> int s;
> if (s >= 0) // VRP saves the day
> {
>    uint u = s;
> }
> ```
>
> ```
> uint u;
>
> if (u > short.max)
>    throw new Exception("Argument out of range");
> // Or `assert`
> short s = u;
> ```

Now, you're talking about comparing signed and unsigned values, which is a
completely different ballgame. Just assigning one to the other really isn't
a problem, and sometimes you _want_ the wraparound. If you assume that it's
always the case that assigning a negative value to an unsigned type is
something that programmers don't want to do, then you haven't programmed in
C enough. And while it could still be done by requiring casts, consider that
every time you do a cast, you're telling the compiler to just shut up and do
what you want, which makes it easy to hide stuff that you don't want hidden
- especially when code changes later.

D purposefully allows converting between signed and unsigned types of the
same or greater size. And based on what he's said on related topics in the
past, there's pretty much no way that you're going to convince Walter that
it's a bad idea. And I really don't see a problem with the current behavior
as far as assignment goes. It's comparisons which are potentially
problematic, and that's where you'd have some chance of getting a warning or
error added to the compiler. If you want to actually have the values check
to ensure that a negative value isn't assigned to an unsigned integer, then
use std.conv.to to do conversions or wrap your integers in types that have
more restrictive rules. IIRC, at least one person around here has done that
already so that they can catch integer overflow - which is basically what
you're complaining about here.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list