Search code examples
cundefined-behavioroperator-precedence

Why are "i = ++i;" and "i = ++i + 2;" undefined behavior?


I found this article: https://en.cppreference.com/w/cpp/language/eval_order

I have no idea why i = ++i; and i = ++i + 2; are undefined behavior.

First example:

int i = 5;

i = ++i;

The result will be still 6.

If i = ++i; is stated as undefined behavior, then i = ++j; should be stated as undefined behavior too (Because assignment can happen before increment?).

Second example:

int i = 5;

i = ++i + 2;

The result will be still 8.

If i = ++i + 2; is stated as undefined behavior, then i = ++j + 2; should be stated as undefined behavior too (because assignment can happen before increment and sum)?


Solution

  • What makes i = ++i; undefined behavior is that you're attempting to both read and write i in the same expression without a sequence point.

    The increment performed by the ++ operator is considered a side effect, as is the assignment performed by the = operator. Having two side effects on the same object, or a side effect and a read on the same object, is what causes problems. It doesn't matter that any possible evaluation order will generate the same result.

    i = ++j; is fine because no object is written to more than once or read and written in the same expression without a sequence point.