logoalt Hacker News

mywittynameyesterday at 8:49 PM1 replyview on HN

Out of curiosity, I checked if gcc would optimize i = i++ out, and it does!


Replies

_kst_yesterday at 11:00 PM

What can be optimized out depends on the context.

If you write:

    int i = 0;
    i = i++;
and never use the value of i, the declaration and assignment are likely to be optimized out. (The behavior of the assignment is undefined, so this is a valid choice).

If you print the value of i, the compiler can still optimize away the computation, but is perhaps less likely to do so.

The solution, of course, is not to write code like that. Decide what you want to do, and write code that does that. "i = i++" will never be the answer to "how do I do this?", and wouldn't be even if the behavior were well defined. If you want i to be 1, write "int i = 1;".