Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post increment question

Tags:

c#

I've this code

static void Main(string[] args)
{
    int x = 20;
    int y = 35;
    x = y++ + x++;
    y = ++y + ++x;
    Console.WriteLine(x);
    Console.WriteLine(y);
    Console.ReadLine();
}

I expected the output to be x = 57 and y = 94. However, when executed it gave me 56 and 93. For some reason the post increment operator is not getting executed in line 3.

Is this because we are assigning the result of expressing in line 3 to x itself? Are there any other scenarios where the post increment operator would not result as expected.

Thanks.

like image 292
stackoverflow Avatar asked Dec 12 '10 10:12

stackoverflow


1 Answers

int x = 20;
int y = 35;
// x = y++ + x++; this is equivalent of
tmp = 35 + 20; y++; x++; x = tmp;
// so here we have x = 55; y = 36
// y = ++y + ++x;
y ++; // 37
x ++; // 56;
y = x + y;
// so here we have y = 93, x = 56;
like image 96
khachik Avatar answered Oct 01 '22 16:10

khachik