The core issue is this:
From my understanding the above code should theoretically copy over
the value of y into x, then finally increment the value of x after the
copy has finished. So it would print out "6".
In fact, the sequencing of the increment is undefined. As in, it is completely undefined as to when x
is incremented, except that it must occur before some specific times. Reading or writing x
during this period of undefined value is undefined behaviour. That's why x++
does not return x
(an lvalue you can write to) but an rvalue you cannot write to- because there's simply nothing useful you can do with x
until the time it's guaranteed to be incremented (except take the address, maybe).
You can still break this rule by referring to x
twice- for example, consider:
void f(int, int);
int main() {
int x = 0;
f(x++, x++);
}
This is also undefined behaviour.