x += x++;

Tags: ,
Add comments

Ok, what does this expression do or mean? First of all: never write something like this in your code. Nobody understands the meaning with a single look and that will lead to confusion and maybe to a bug in your software someday.

Now let’s take a deeper look. First you may think about the difference between x++ and ++x. If you write it as a single statement both expressions are equal, but if you use it as a part of a complex expression the first will evaluated to the value of x before increasing it; the second one will evaluate to the new value of x. So y = x++; leads to a different result for y as y = ++x;.

x+=a simply is a ‘shortcut’ for x=x+a.

Now let’s do it step by step. For example x is 5. Then first x will be increased by one to 6 but the old value will go into the formula that remains as x=x+5. Since x was increased before the result will be 11.

If you think that is all right, than please take a break and test it with your favorite compiler. If you are a C or C++ guy you will in fact receive 11 as an answer and everything is fine. But if you are a C# or java guy x will be 10. Why?

.Net as well as the Java Runtime are stack machines. The expression will be put on the stack step by step before evaluating the whole thing. At that time x is 5. x will be changed to 6 by the x++ part, but that only happens in the main memory. The old value (5) is still on the stack. After executing the whole expression the changed x will be overwritten by 10 (5+5).

And once again: NEVER write code like this!

One Response to “x += x++;”

  1. Yikaton Says:

    I don’t know about C# and Java, but wrt C and C++ the only correct statement is “NEVER write code like this!”
    x += x++ is simply undefined for basic types (int, double, …) http://c-faq.com/expr/ieqiplusplus.html

    Why am I the first to comment? maybe only Google (that gave me this page) has read it. So this will be my boyscout good did of today: correct one C-misconception for one person.
    Sigh …

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in