Is the behaviour of i = i++ really undefined?

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.

Leave a Comment