Why is int implicitly convertible to ulong?

Jonathan M Davis jmdavisProg at gmx.com
Sun Feb 16 20:40:36 PST 2014


On Sunday, February 16, 2014 21:35:01 Hannes Steffenhagen wrote:
> isImplicitlyConvertible!(int,ulong) is true. Maybe this is just
> me, but I get the impression that this is quite nuts. Why is an
> implicit conversion from a signed to an unsigned type possible?
> The other way round would be at least somewhat understandable if
> there's a static check that the values actually fit.

signed to unsigned conversions (and vice versa) are implicit as are 
conversions from smaller integral types to larger integral types. Converting 
from smaller integral types to larger really doesn't cause any problems, but 
the signed to unsigned (or vice versa) can cause issues - one of the biggest 
of those being the comparison of signed and unsigned values, and IIRC, there 
was some discussion on making that a warning or error. However, while there 
are occasional problems from the conversion being implicit, if it weren't 
implicit, you'd be forced to cast a lot more when the signed and unsigned 
types interact, which would lead to messier code and could actually increase 
the number of bugs, because if you got in the habit of casting everywhere to 
get the signed to unsigned conversions to work, you'd risk accidentally doing 
stuff like casting a ulong to int and losing data, since the compiler would 
assume that you knew what you were doing with the cast.

So, it's a tradeoff, and neither making the signed to unsigned (or vice versa) 
conversions explicit nor implicit would be without problems. Walter went with 
it being implicit, which matches what C does. However, unlike C, conversions 
that actually lose data (e.g. long -> int) do require casts so that it's 
easier to catch those problems. But no data is actually lost with a sign 
conversions, as casting it back to what it was will result in the same value 
(unlike with converting to a smaller integral value).

Of slightly bigger concern IMHO is that bool and the character types are all 
treated as integral types, which is at times useful but also risks some 
entertaining bugs. But again, it's a matter of tradeoffs. If they required 
casts when interacting with integral types, then a lot more casting would be 
required, risking a different set of bugs. There really isn't a right answer 
as to whether the conversions should be implicit or explicit. It just comes 
down to the tradeoffs that you prefer.

- Jonathan M Davis


More information about the Digitalmars-d mailing list