C++ Undefined Behavior – Is i = i++ Really Undefined?

c++language-lawyer

Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)

According to c++ standard,

i = 3;
i = i++;

will result in undefined behavior.

We use the term "undefined behavior" if it can lead to more then one result. But here, the final value of i will be 4 no matter what the order of evaluation, so shouldn't this really be called "unspecified behavior"?

Best Answer

The phrase, "…the final value of i will be 4 no matter what the order of evaluation…" is incorrect. The compiler could emit the equivalent of this:

i = 3;
int tmp = i;
++i;
i = tmp;

or this:

i = 3;
++i;
i = i - 1;

or this:

i = 3;
i = i;
++i;

As to the definitions of terms, if the answer was guaranteed to be 4, that wouldn't be unspecified or undefined behavior, it would be defined behavior.

As it stands, it is undefined behaviour according to the standard (Wikipedia), so it's even free to do this:

i = 3;
system("sudo rm -rf /"); // DO NOT TRY THIS AT HOME … OR AT WORK … OR ANYWHERE.