Yoni Mantzur
Yoni Mantzur

Reputation: 42

Post-increment in assignment to reference c++

Assume I have this code:

int i = 2;
int &ref = i++;

Now, I understand that reference can not be initiaizied with rvalue, but I can not understand why ref isn't initialized with lvalue, meaning here, i, and after that i incremented.

Moreover, in the following case:

   int i = 2;
   const int &ref = i++;
   cout << ref << endl;

2 will be printed, and it means that ref initialized with i before increment, i.e. initialized with lval. After that ref is incremented, but ref is const.

Can someone explain me what I am missing here?

Upvotes: 0

Views: 1551

Answers (3)

Alok S
Alok S

Reputation: 1

Post incrementing an int does not return in lvalue. i++ returns a temporary copy before incrementing itself.

Upvotes: 0

MikeMB
MikeMB

Reputation: 21166

i++ doesn't return i, but a temporary copy, that was taken before i got incremented. That's why it is called POST increment, because it increments thew variable AFTER it retained a copy of the current state.

Upvotes: 2

TartanLlama
TartanLlama

Reputation: 65630

Post-incrementing an int does not result in an lvalue. A hypothetical implementation might look like this:

int operator++(int& i) {
    int temp = i;
    ++i;
    return temp;
}

As you can see, a copy needs to be made and that is returned by value.

Pre-increment does result in an lvalue because no copy is required, so the result is a reference to the original.

Your second example works because rvalues can bind to references-to-const.

Upvotes: 4

Related Questions