
If i = 0, why is i += i++ 0? - ivoflipse
http://stackoverflow.com/questions/13516689/if-i-0-why-is-i-i-0
======
Claudus
The answer, from the same site:

[http://stackoverflow.com/questions/24853/what-is-the-
differe...](http://stackoverflow.com/questions/24853/what-is-the-difference-
between-i-and-i)

" _++i will increment the value of i, and then return the incremented value._
"

" _i++ will increment the value of i, but return the pre-incremented value._ "

~~~
keefe
yep that's 101 stuff eh?

~~~
yen223
It's a bit more subtle than that.

    
    
      i += i++;
      Console.write(i);
    

could print 0, 1, or 2 depending on the order in which

    
    
      i++
    

and

    
    
      i += <value>
    

is evaluated. From the winning answer, what's really happening is:

    
    
      int i = 0;
      i = i + i;
      i + 1; // Note that you are discarding the calculation result
    

This kind of nonsense is the reason why Python doesn't have prefix and postfix
increments.

------
sn
Using gcc or g++ I get "1" not "0" for that expression, as I would intuitively
expect. But this is undefined behavior in c/c++: tmp.c: In function ‘main’:
tmp.c:3:5: warning: operation on ‘i’ may be undefined [-Wsequence-point]

~~~
fragmede
Eh?

int main() { int i=0; return i += i++; }

Returns 0, as expected.

------
yen223
Why did they close the question?

~~~
SmileyKeith
I still never understand why they close some questions. Quite often I find a
very useful answer that's posted on a closed question.

------
lsiebert
This is for c# not c or c++, fyi

------
krob
this is correct. i = 0; i+=i++;

(0) + (0)++ = 0 next time around (1) + (1)++ = 2

~~~
yen223
Unfortunately this is not correct.

If you run

    
    
      for (int x = 0; x < 10; x++)
      {
        i += i++;
        Console.WriteLine(i);
      }
    

i is always 0.

------
crpatino
undefined behavior, isn't it? might as well be 42.

