-1

Possible Duplicate:
Explaining post-increment in C#

Consider the following C# code:-

int i = 2;
i = i++;
Console.WriteLine(i);

I am getting the output as 2. Why there is no effect of i = i++?

Community
  • 1
  • 1
Jainendra
  • 24,713
  • 30
  • 122
  • 169
  • http://stackoverflow.com/questions/2371118/explain-working-of-post-and-pre-increment-operator-in-java – Gopi Jun 04 '12 at 08:04
  • This is the correct dup: http://stackoverflow.com/questions/4287839/c-sharp-increment-operator-questionwhy-am-i-getting-wrong-output – Tim Schmelter Jun 04 '12 at 08:05
  • See its a confusing ques (Read Interview type). If = takes precedence first, then increment happens afterwards means i should be 3. If ++ takes precedence first then after incrementing it should assign 3 in i. – Nikhil Agrawal Jun 04 '12 at 08:08
  • It will compiled into int i = 2; int topOfStack = i; i++; i = topOfStack; – Viacheslav Smityukh Jun 04 '12 at 08:12

2 Answers2

0

Depending on where you put the +-operators, the value assigned is incremented before or after:

i = ++i;

This way i is counted up before assigned.

i = i++;

This way i is counted up after assigned.

Mario S
  • 11,715
  • 24
  • 39
  • 47
0

Because the = operator takes precedence first.

MSDN: Operator precedence and associativity.

Try this one:

int i = 2;
i = ++i; // or write just ++i;
Console.WriteLine(i);
papaiatis
  • 4,231
  • 4
  • 26
  • 38