i = i++ doesn't increment i. Why?

Armen Tsirunyan picture Armen Tsirunyan · Jul 16, 2011 · Viewed 13.5k times · Source

Possible Duplicates:
Why does this go into an infinite loop?

Things like i = i++ have undefined behavior in C and C++ because the value of a scalar object is changes twice within the same expression without intervening sequence point.

However I suppose that these kind of expressions have well-defined behavior in C# or Java because AFAIK the evaluation of argument goes left to right and there are sequence points all over.

That said, I'd expect i = i++ to be equivalent to i++. But it's not. The following program outputs 0.

using System;
class Program
{
    static void Main(string[] args)
    {
        int i = 0;
        i = i++;
        Console.WriteLine(i);
    }
}

Could you help me understand why?

Disclaimer: I am fully aware that whether or not the behavior of above-mentioned constructs is defined, they are silly, useless, unreadable, unnecessary and should not be used in code. I am just curious.

Answer

CodesInChaos picture CodesInChaos · Jul 16, 2011

The behavior is well defined in C# and the evaluation order is:

  1. Left side i is evaluated to the variable i
  2. Right side is evaluated to 0, and i is incremented (now i==1)
  3. The assignment is executed, it sets i to 0. (now i==0)

The end result is i==0.

In general you first create an expression tree. To evaluate it you evaluate first the left side, then the right side and finally the operation at the root. Do that recursively.