Question

I created a basic console application to make such a test.

        short val = 32767;

        val++;

        Console.WriteLine(val);

This gives me -32768 as an expected result

        short val = 32767;

        val = val +1;

        Console.WriteLine(val);

But this gives me this error

Error 1 **Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)

I am curious about what causes this ?

Thanks in advance,

Was it helpful?

Solution

The result of a short + short operation is defined as an int. In the first case, the compiler is going ahead and applying a (short) cast on the result of the increment, but it is not in the second.

short myShort = 1;
int resultA = myShort + myShort; // addition returns an integer
short resultB = myShort++; // returns a short, why? 

// resultB is essentially doing this
short resultB = (short)(myShort + 1);

In addition to the link provided by Joel in the comments, you can also refer to section 7.3.6.2 of the C# 4.0 language specification that lays out the rules for binary numeric promotions (covering expressions of the form a = b + c;) and also 7.6.9 that covers pre- and postfix operators.

OTHER TIPS

Adding two shorts will return an int.

The += and ++ operators behave differently and work as expected.

The result of addition of two shorts, or a short and an int, as in your case, is always of type int, which needs to get converted back to short in order to be assigned to val.

The reason why this is so is that the sum of two shorts, or a short and an int may not fit into short, so is always int. Consider this;

short x = 30000;
short y = 30000;

int z = x+y; // would you really want to get a number other than 60000 here?  
short s = (short)(x+y); //if you want modulo 2^16

The 1 in your line:

val = val +1;

is an int implicitly, so the result of val + 1 is an int. You're trying to assign that value a short, and that can't be done implicitly because you'd risk losing some precision.

Using val + 1 makes it think it's an integer.

Using:

    short val = 32767;

    val = (short) (val + 1);

    Console.WriteLine(val);

Should work.

The evaluation of numbers defaults to int (Int32).

In your case here, you're trying to add an short(Int16) to an int(Int32) type. This correctly throws an error.

val = val +1;

Here, 1 is of type int so is val + 1.

When you run val++, you just increment the value stored in the variable.

When you run val=val+1, 1 is an int by default so the compiler considers both values to be ints and returns an int with the value val+1. Then it fails to put it back into val because an int is to large to store in a short.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top