byte + byte = int: why?

Adam D. Ruppe destructionator at gmail.com
Fri Jan 18 17:24:27 UTC 2019


On Friday, 18 January 2019 at 17:09:52 UTC, Mek101 wrote:
> Meaning that the byte type doesn't have a + operator.

Well, it DOES have a + operator, it just returns int that can be 
squished to a size if and only if the compiler proves it fits.

A bit of background: the C language was designed on a machine 
that did arithmetic in a fixed size register. It defined `int` to 
be at least the size of this register and for all arithmetic to 
be expanded to at least that same size.

In other words, anything smaller than an `int` is converted to an 
`int` before operations are done to it.

D (and C# via the CLR being designed in the same way, among other 
languages) inherited this rule from C. So a + a will be converted 
to int for anything smaller than int, like byte or short.


Now the difference between C and D is that C would let you assign 
that result right back to the small type without complaining, 
whereas D issues the error. Why?

The reason is the carry bit. Consider the case of 127 + 127. The 
answer is too big to fit in a signed byte; one bit will carry 
over and be dropped. D considers this potential data loss and 
wants you to make a conscious choice about it via an explicit 
cast.

If the compiler knows for certain the numbers will fit, it allows 
it. Like 64 + 5 will implicitly cast to a byte because the 
compiler sees the size of the result. But for runtime values, it 
is usually unsure and forces you to do the cast.

  temp[fowardI] = cast(byte) (temp[fowardI] + temp[backwardI]);

that will work.


More information about the Digitalmars-d-learn mailing list