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.
The behavior is well defined in C# and the evaluation order is:
i
is evaluated to the variable i
i
is incremented (now i==1
)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.