byte + byte = int: why?
Ali Çehreli
acehreli at yahoo.com
Sun Aug 29 15:42:18 UTC 2021
On 1/18/19 9:09 AM, Mek101 wrote:
> source/hash.d(11,25): Error: cannot implicitly convert expression
> `cast(int)temp[fowardI] + cast(int)temp[backwardI]` of type `int` to
`byte`
Others suggested casting as a solution which works but it will hide
potential errors.
Depending on the situation, you may want to use std.conv.to, which does
a value range check and throws an exception to prevent an error:
byte foo(byte a, byte b) {
import std.conv : to;
return (a + b).to!byte;
}
void main() {
foo(42, 42); // Works
foo(100, 100); // Throws ConvOverflowException
}
Of course, because of the checks, 'to' is slower than casting blindly.
Ali
More information about the Digitalmars-d-learn
mailing list