4 ms·
If i = 0, why is i += i++ 0?
- Claudus 14y agoThe answer, from the same site: http://stackoverflow.com/questions/24853/what-is-the-difference-between-i-and-i http://stackoverflow.com/questions/24853/what-is-the-differe... "++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 14y agoyep that's 101 stuff eh?
- yen223 14y agoIt'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.
- deleted 14y ago[deleted]
- sn 14y agoUsing 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 14y agoEh? int main() { int i=0; return i += i++; } Returns 0, as expected.
- crpatino 14y agoundefined behavior, isn't it? might as well be 42.
- pootch 14y agoIm glad we are getting this out of the way on HN, super critical to define prefix and postfix operators. Maybe rename the site to slacker news? ALSO can we please not entertain stackoverflow tom foolery, kindergarten cop programming questions on HN?
- lsiebert 14y agoThis is for c# not c or c++, fyi
- yen223 14y agoWhy did they close the question?
- SmileyKeith 14y agoI still never understand why they close some questions. Quite often I find a very useful answer that's posted on a closed question.
- krob 14y agothis is correct. i = 0; i+=i++; (0) + (0)++ = 0 next time around (1) + (1)++ = 2
- yen223 14y agoUnfortunately this is not correct. If you run for (int x = 0; x < 10; x++) { i += i++; Console.WriteLine(i); } i is always 0.