Why there is too many uneccessary casts?
Steven Schveighoffer
schveiguy at yahoo.com
Tue Jun 11 09:05:28 PDT 2013
On Tue, 11 Jun 2013 07:46:11 -0400, Temtaime <temtaime at gmail.com> wrote:
> No. I means, that
>
> uint a = uint.max;
> uint b = a + 1;
> writeln(b);
>
> Works OK.
> Why? Compiler doesn't know if a + b fits in uint, right?
> Then why overflow with ints are accepted?
CPU performs math at int level. So even if you add two ubytes, they are
added at integer level.
For instance, this is valid, and does not produce a truncated uint:
ubyte x = ubyte.max;
uint y = x + x;
assert(y == 255 + 255);
Essentially the compiler is making sure you wanted to throw away that
extra precision that it had to create anyways because that's what the CPU
supports.
It can take some getting used to.
Note that += does not have this problem:
ubyte c = k;
c += 1; // ok
This I find extremely inconsistent...
-Steve
More information about the Digitalmars-d-learn
mailing list