Why is incrementing and assigning to a reference, not change the value?

Viewed 110

I am not able to understand, why the output of the code is not what I was expecting.

#include <iostream>
using namespace std;
int main()
{
    int m = 2, n = 6;
    int &x = m;
    int &y = n;
    m = x++; 
    x = m++;
    n = y++;
    y = n++;
    cout<< m << " " << n; 
    return 0; 
}

I was expecting 4 8

2 Answers

This line:

m = x++; 

is equivalent to:

x = x++;

since m is a reference to x.

From c++17, the right hand side is evaluated first, resulting in 2. Then x is incremented to 3. Then the assignment of the right hand side value to the left hand side is done. But this uses the old value of the right hand side, which is 2. So the above statement effectively does nothing.

Before c++17,

m = x++;

is undefined behavior.

Notice how the operators are post-increment and not pre-increment... You're basically doing nothing.

m = x++; means that increment x (i.e. m) but return the old value of x (i.e. m). Assignment takes place after the increment and return of old value and the old value is what ends up getting assigned. So, you end up essentially with a bunch of self-assignments.

Related