On Thursday, November 05, 2015 09:33:39 ixid via Digitalmars-d-learn wrote:
> In C++ I can add two shorts together without having to use a cast
> to assign the result to one of the two shorts. It just seems
> super clunky not to be able to do basic operations on basic types
> without casts everywhere.

That's why we have value range propagation - so that when the compiler can
prove that the result will fit in the smaller type, it'll let you assign to
it. Perhaps the compiler should do more with that than it currently does,
but it's definitely help reduce the number of casts that are required for
narrowing conversions.

But allowing implicit narrowing conversions is a source of bugs, which is
why languages like D, C#, and Java have all made narrowing conversions
illegal without a cast. Yes, that can be annoying when you need to do math
on a byte or short, and you want the result to end up in a byte or short,
but it prevents bugs. It's a tradeoff. Fortunately, VPR improves the
situation, but we're not going to be able to prevent narrowing bugs while
still allowing implicit narrowing conversions. C/C++ went the route that
requires fewer casts but more easily introduces bugs, whereas D, Java, and
C# went the route where it's harder to introduce bugs but doing arithmetic
on types smaller than int gets a bit annoying. Personally, I think that the
route that D has taken is the better one, but it is a matter of opinion and
priorities.

But if it's important enough to you to not need to cast for arithmetic
operations on small integer types, you can always create a wrapper type that
does all of the casts for you so that you get the implicit conversions.

- Jonathan M Davis

Reply via email to