1

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)?

Malan Olan
  • 49
  • 3

1 Answers1

6

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    can you explain what is a sequence point? – Adam May 21 '20 at 11:39
  • @Adam Sequence point guarantees that left operand will be evaluated before second operand - for example comma is sequence point. For example: a, b. Comma guarantees that operand (variable) a will be evaluated before operand b. – Malan Olan May 21 '20 at 11:48