[Issue 9430] short and byte implicitly cast to integer with binary arithmetic ops

d-bugmail at puremagic.com d-bugmail at puremagic.com
Wed Jan 30 20:31:40 PST 2013


http://d.puremagic.com/issues/show_bug.cgi?id=9430


Jonathan M Davis <jmdavisProg at gmx.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|NEW                         |RESOLVED
                 CC|                            |jmdavisProg at gmx.com
         Resolution|                            |INVALID


--- Comment #2 from Jonathan M Davis <jmdavisProg at gmx.com> 2013-01-30 20:31:37 PST ---
This is expected behavior. It's the same as C/C++ (and probably Java and C#,
though I don't remember for sure). Arithmetic operations on integral types
result in the largest integral type in the expression or in int if the integral
types are smaller than int. And as D requires explicit casts for narrowing
conversions (unlike C/C++), a cast is then required to assign to a variable of
an integral type smaller than int. So, C/C++ do exactly the same thing as D is
doing here, but they allow the implicit cast back to the smaller type, whereas
D does not. Unlike C/C++, D _does_ do range propagation such that if it can
determine for certain that the result would fit in the smaller type, the cast
isn't required, but that generally requires that integer literals be involved.

+=, -=, etc. work because there's no way to do the cast. If you had

a = a + b;

then you could do

a = cast(byte)(a + b);

but there's no place to put the cast in

a += b;

And you're effectively asking for the cast, because the result is being
reassigned to a. Whereas with

a = a + b;

the expression on the right hand side (and its type) are evaluated before the
assignment takes place, so the fact that you're assigning the result of the
expression to a has no effect on how its evaluated or what its type is.

While this behavior might be a bit annoying, it follows from the fact that D
requires explicit casts for narrowing conversions, and it generally prevents
bugs.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list