Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

Mehul Sanghvi
Ranch Hand
Posts: 134
Hi,

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
Posts: 732
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.

here

Jeff Albertson
Ranch Hand
Posts: 1780

Stuart Goss
Ranch Hand
Posts: 169
Hi,

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 ]

Jeff Albertson
Ranch Hand
Posts: 1780
My New Year's resolution is to be less terse