"val ++" vs "val = val + 1" What is the exact difference?

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

        short val = 32767;

        val++;

        Console.WriteLine(val);

This gives me -32768 as expected result

        short val = 32767;

        val = val +1;

        Console.WriteLine(val);

But it gives me this error

Error 1 ** It is not possible to implicitly convert the type 'int' to 'short'. Explicit conversion exists (are you skipping listing?)

I wonder what causes this?

Thanks in advance,

+3
source share
8 answers

The result of the operation short + shortis defined as int. In the first case, the compiler goes ahead and applies the cast (short)to the result of the increment, but 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);

, , 7.3.6.2 # 4.0, ( a = b + c;), 7.6.9, - .

+12

short int.

+= ++ - .

+2

, short int, , int, , val.

, , , int , int. :

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
+1

1 :

val = val +1;

int , val + 1 int. , , .

0

val + 1 .

:

    short val = 32767;

    val = (short) (val + 1);

    Console.WriteLine(val);

.

0

- int (Int32).

(Int16) int (Int32). .

0
val = val +1;

1 int, val + 1.

0

val++ , .

When you start val=val+1, the default 1is int, so the compiler considers both values intsand returns intwith a value val+1. Then he cannot bring it back in val, because it intmust be large for storage in a short form.

0
source

All Articles