I have a code:
static short Sum(short a, short b)
{
return a + b;
}
And it does not compile, saynig cannot convert ‘int’ to ‘short’. I am maybe really tired today but I cannot see the issue!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s just the way the language is defined. The + operator on integer types is defined for:
Operands are promoted as required.
Now as for the reasons why it’s defined that way – I don’t know, to be honest. I don’t buy the argument of “because it could overflow” – that would suggest that
byte + byteshould be defined to returnshort, and thatint + intshould returnlong, neither of which is true.I’ve heard somewhere that it could be performance related, but I wouldn’t like to say for sure. (Perhaps processors typically only provide integer operations on 32 and 64 bit integers?)
Either way, it doesn’t really matter why it’s the case – it’s just the rules of the language.
Note that the compound assignment operators have an implicit conversion back to the relevant type, so you can write: