On Tue, 11 Jun 2013 13:15:11 +0200, Simen Kjaeraas
<simen.kja...@gmail.com> wrote:
On Tue, 11 Jun 2013 12:39:47 +0200, Temtaime <temta...@gmail.com> wrote:
There is overflow and it can be with int too.
It's standard behavior.
Indeed. And a class is a void* is an int is a char is a double? That's
perfectly possible - it's all just memory anyway. D has chosen to do
it like this to prevent common errors. If you think the cast stands
out like a sore thumb, use:
ubyte k = 10;
ubyte c = (k + 1) & 0xFF;
That way, value range propagation ensures the result fits in a ubyte,
and the code compiles happily.
Also worth noting: both & 0xFF and cast(ubyte) shows that the programmer
has considered the possibility of overflow (or just programmed blindly,
but let's assume a rational programmer), something your original code did
not.
Looking at this code:
ubyte a = foo();
ubyte b = a + 1;
doSomethingWith(b);
It's not possible for me to know if that code works correctly if foo()
returns 255 - perhaps it should actually be saturated (255+1 == 255),
perhaps it should even throw an exception. With this code:
ubyte a = foo();
ubyte b = cast(ubyte)(a + 1); // or (a + 1) & 0xFF;
doSomethingWith(b);
The programmer has documented something: If this causes an overflow,
the value in b is still correct. Explicit is better than implicit.
--
Simen