Integer summing blues, short += short problem

后端 未结 5 846
野趣味
野趣味 2020-11-22 10:42

Program in C#:

short a, b;
a = 10;
b = 10;
a = a + b; // Error : Cannot implicitly convert type \'int\' to \'short\'.

// we can also write this code by usin         


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 11:30

    This is because += is implemented as an overloaded function (one of which is a short, and the compiler chooses the most specific overload). For the expression (a + b), the compiler widens the result to an int by default before assigning.

提交回复
热议问题