www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - ushort arithmetic question

reply Jonathan Crapuchettes <jcrapuchettes gmail.com> writes:
Shouldn't this code work? Looking at the arithmetic conversions section 
of http://dlang.org/type.html, point 4.1 makes me think that I shouldn't 
be getting the error since they are the same type.

void main()
{
    ushort v1 = 1;
    ushort v2 = 1;
    ushort v3 = v1 + v2;
}

test.d(5): Error: cannot implicitly convert expression (cast(int)v1 + cast
(int)v2) of type int to ushort
Oct 25 2013
parent reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 10/25/2013 11:45 AM, Jonathan Crapuchettes wrote:
 Shouldn't this code work? Looking at the arithmetic conversions section
 of http://dlang.org/type.html, point 4.1 makes me think that I shouldn't
 be getting the error since they are the same type.

 void main()
 {
      ushort v1 = 1;
      ushort v2 = 1;
      ushort v3 = v1 + v2;
 }

 test.d(5): Error: cannot implicitly convert expression (cast(int)v1 + cast
 (int)v2) of type int to ushort
But there is 4.0 before 4.1: :) 4. Else the integer promotions are done on each operand, followed by: 1. If both are the same type, no more conversions are done. Note "integer promotions are done on each operand". In other words, e.g. there is no arithmetic operation on a ushort. The expression v1 + v2 is performed as two ints. Ali
Oct 25 2013
parent Jonathan Crapuchettes <jcrapuchettes gmail.com> writes:
On Fri, 25 Oct 2013 11:51:03 -0700, Ali Çehreli wrote:

 On 10/25/2013 11:45 AM, Jonathan Crapuchettes wrote:
 Shouldn't this code work? Looking at the arithmetic conversions section
 of http://dlang.org/type.html, point 4.1 makes me think that I
 shouldn't be getting the error since they are the same type.

 void main()
 {
      ushort v1 = 1; ushort v2 = 1; ushort v3 = v1 + v2;
 }

 test.d(5): Error: cannot implicitly convert expression (cast(int)v1 +
 cast (int)v2) of type int to ushort
But there is 4.0 before 4.1: :) 4. Else the integer promotions are done on each operand, followed by: 1. If both are the same type, no more conversions are done. Note "integer promotions are done on each operand". In other words, e.g. there is no arithmetic operation on a ushort. The expression v1 + v2 is performed as two ints. Ali
Thank you for pointing that out for me. I missed that part. Jonathan
Oct 25 2013