Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

increment

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.

like image 712
Armen Tsirunyan Avatar asked Jul 16 '11 08:07

Armen Tsirunyan


People also ask

What is ++ i and i ++ in C?

++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.

How do you stop a loop from incrementing?

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.


1 Answers

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.

like image 174
CodesInChaos Avatar answered Oct 18 '22 19:10

CodesInChaos