The above code gives a compile time error of type mismatch, cannot convert int to short. If c is declared as int then the output is 1. And if casting is removed the output is 32769. Hence int the code
the value on right hand side is evaluated to 1, which is logical.
The question is: Why is that value not assigned to type short @ //1
Regards, Mehul.
Roy Ben Ami
Ranch Hand
Joined: Jan 13, 2002
Posts: 732
posted
0
As you say the sum of the two numbers is 32769 Since The maximum positive number a short can hold is 32767 then you can't put it into a short (only int and above).
Now let's look at what happens in each case:
int x=a+b => Here you just get 32769 like you noticed because thats the sum of the numbers.
int x=(short)a+b => here you still get 32769 but because of the cast to short we only look at the lower 15 bits which have only 1 in them, so we get 1.
as Jeff writes, the code will work with the "short cast" applied to the entire addition expression.
WHY?: because the compiler will convert all types in an integer maths expression to the "int" type (if the types aren't int or long). So your "a" and "b" are temporarily copied to ints during the addtion process. You need to recast the entire expression, just like Jeff suggests.
Stuart [ December 30, 2005: Message edited by: Stuart Goss ]