ushort + ushort = int?
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Mon Aug 20 09:56:13 UTC 2018
On Monday, August 20, 2018 3:19:04 AM MDT Andrey via Digitalmars-d-learn
wrote:
> On Monday, 20 August 2018 at 08:49:00 UTC, rikki cattermole wrote:
> > Yes. On x86 int's will be faster just an FYI so it does make
> > sense to use them for computation.
>
> Inconveniently always use casts. Why in D one decided to do in
> such way?
It's a combination of keeping the C semantics (in general, C code is valid D
code with the same semantics, or it won't compile) and the fact that D
requires casts for narrowing conversions. When you add two shorts in C/C++,
it converts them to int just like D does. It's just that C/C++ has implicit
narrowing casts, so if you assign the result to a short, it then converts
the result to short even if that means that the value could be truncated,
whereas D requires that you explicitly cast to convert to int rather than
silently truncating.
It does prevent certain classes of problems (e.g. there are plenty of bugs
in C/C++ due to implicit narrowing conversions), but it can also get pretty
annoying if you're doing much math on integer types smaller than int, and
you either know that they aren't going to overflow or truncate, or you don't
care that they will. But if you're only doing math on such small integeral
types occasionally, then it pretty much just means that once in a while, you
get briefly annoyed when you forget to add a cast, and the compiler yells at
you.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list