byte + byte = int: why?

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Jan 18 17:37:21 UTC 2019


On Fri, Jan 18, 2019 at 05:26:35PM +0000, Mek101 via Digitalmars-d-learn wrote:
> On Friday, 18 January 2019 at 17:15:09 UTC, Steven Schveighoffer wrote:
> > What is 127 + 127? Answer: 254. Which if converted to a byte is
> > -127.  Not what you might expect if you are doing addition.
> 
> Quite similar to int.max + int.max
> 
> > In fact, D promotes all integral types smaller than int to int to do
> > arithmetic. And if the result might not fit into what you are
> > assigning it to, it requires a cast or mask.
> 
> Then why isn't int + int = long? If i did the example above, they
> wouldn't fit in a int for sure, yet the result is of the same type.
> Why should byte be any different?

It's historical baggage from C's integer promotion rules, that's all
there is to it.  Many people seem to think that's a good thing. I
personally think it sucks, and so I've written a nopromote module to
work around the autopromotion (see my other post).

OTOH if you're concerned about int overflow, just cast to long:

	int x = int.max, y = int.max;
	auto result = cast(long)x + y;

Of course, eventually you run out of options, e.g., if you try to add
ulong.max to ulong.max.  Generally most people won't run into that, but
if you're concerned about that, you could pull out the big guns and
import std.bigint. :-D


T

-- 
Music critic: "That's an imitation fugue!"


More information about the Digitalmars-d-learn mailing list