Search code examples
.net.net-assemblyshort

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


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,


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.