Deprecate implicit conversion between signed and unsigned integers
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Thu Feb 20 11:33:50 UTC 2025
On Thursday, February 20, 2025 1:35:10 AM MST Dom DiSc via dip.ideas wrote:
> On Thursday, 20 February 2025 at 03:14:08 UTC, Jonathan M Davis
> wrote:
> > ~x would probably implicitly convert, but like you, I'd have to
> > test it.
>
> ~ on small types will generate a lot of higher set bits, so no,
> it will NOT convert back to same type. Same problem with -
Actually, now that I think about it more, in this case, if it's doing the
operation on int, then the result is _very_ different from if it had
actually done the operation on (u)byte or (u)short. With most arithmetic
operations, the result is the same except that you don't have overflow
issues if you're operating on int with large bytes or shorts like you would
if you'd operated directly on the type (though of course, casting back can
then truncate the result), but with ~, the result is _very_ different. I
don't even recall the last time that I used ~ and clearly didn't think it
through enough, since I'm used to the result being the same so long as the
result fits.
> This is so bad, I'm honestly surprised that it works with +
It doesn't work. This fails to compile
byte b1 = 42;
byte b2 = b1 + 120;
complaining that it can't convert from int to byte. The same hapens with
byte b1 = 0;
byte b2 = ~b1;
However, this does compile
byte b1 = 42;
byte b2 = ~b1;
So, I guess that it sees that it's doing enough data flow analysis to see
that b1 is 42 and that ~b1 would fit into a byte, so it allows the
conversion. Curiously though,
byte b1 = 42;
byte b2 = b1 + 1;
does not compile even though the result would fit, whereas
byte b1 = 42;
byte b2 = b1 + 0;
does compile. So, it would appear that VRP is being a tad weird with its
decisions, but it does seem to be rejecting the result when it wouldn't fit
(and of course, if it doesn't know the values, it's going to have to assume
that the result doesn't fit).
- Jonathan M Davis
More information about the dip.ideas
mailing list