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.
++i will increment the value of i , and then return the incremented value. i = 1; j = ++i; (i is 2, j is 2) i++ will increment the value of i , but return the original value that i held before being incremented.
If so, it's an easy fix: just remove the incrementing statement that runs at the end of every loop iteration. That way you're left with only the one increment line in the if statement. By the way, do note that there's no point in using a for loop that only ever has one iteration.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With