On 1/18/19 12:09 PM, Mek101 wrote:
I have the following line of code:

     temp[fowardI] = temp[fowardI] + temp[backwardI];

Where temp is a byte array (byte[]). When I try to compile it dmd gives me this error:

    source/hash.d(11,25): Error: cannot implicitly convert expression `cast(int)temp[fowardI] + cast(int)temp[backwardI]` of type `int` to `byte`
/usr/bin/dmd failed with exit code 1.

Meaning that the byte type doesn't have a + operator. I know by experience that the pitfall came from C# (which I also use), and the absence of the operator was justified because the CLI didn't support addition between values smaller than an int, and also byte wasn't enough "numberish" to be used as such, and I should have used int instead.

But why the D language doesn't implement the operator on byte?

What is 127 + 127? Answer: 254. Which if converted to a byte is -127. Not what you might expect if you are doing addition.

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.

See documentation here: https://dlang.org/spec/type.html#usual-arithmetic-conversions

-Steve

Reply via email to