i = i++ doesn't increment i. Why? [duplicate]

天涯浪子 提交于 2019-11-27 13:29:27

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.

The result of the post-increment expression i++ is the original value of i. So after i++ has been evaluated (incrementing i), you assign the old value of i to ... i.

Just use

i++;

;)

i = ++iis the code that does what you think is going on here. i++ actually behaves a bit differently.

With i++, the value of i is increased, but the value of i++ is not the new value of i, it's the previous value. So when you do i = i++, you're saying "increase the value of i, then set i to the old value".

Martin Törnwall

Well, the right-hand side expression must be evaluated before the assignment can take place. Now, i++ will evaluate to the current value of i, and i's value will subsequently increase by one. However, the assignment hasn't been performed yet, and when it is, it will overwrite the current value of i (1) with whatever the rhs expression evaluated to, which in your case was 0.

The key difference is between ++i (pre-increment, which evaluates to the new value of i after incrementing) and i++, or post-increment, which evaluates to the current value of i before incrementing.

Had you used ++i instead, the right-hand side expression would have evaluated to 1, resulting in i == 1.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!