c# - Integer summing blues, short += short problem -
program in c#:
short a, b; = 10; b = 10; = + b; // error : cannot implicitly convert type 'int' 'short'. // can write code using arithmetic assignment operator given below += b; // running successfully, why? console.write(a);
there 2 questions here. first "why short plus short result in int?"
well, suppose short plus short short , see happens:
short[] prices = { 10000, 15000, 11000 }; short average = (prices[0] + prices[1] + prices[2]) / 3; and average is, of course, -9845 if calculation done in shorts. sum larger largest possible short, wraps around negative, , divide negative number.
in world integer arithmetic wraps around more sensible calculations in int, type have enough range typical calculations not overflow.
the second question is:
- short plus short int
- assigning int short illegal
- a +=b same = + b
- therefore short += short should illegal
- so why legal?
the question has incorrect premise; third line above wrong. c# specification states in section 7.17.2
otherwise, if selected operator predefined operator, if return type of selected operator explicitly convertible type of x, , if y implicitly convertible type of x or operator shift operator, operation evaluated x = (t)(x op y), t type of x, except x evaluated once.
the compiler inserts cast on behalf. correct reasoning is:
- short plus short int
- assigning int short illegal
- s1 += s2 same s1 = (short)(s1 + s2)
- therefore should legal
if did not insert cast impossible use compound assignment on many types.
Comments
Post a Comment