2
votes
#include<iostream.h> 
int main()
{
    int m = 2;
    int &x = m++;
    cout<<m;
    return 0; 
}

this code should gives OUTPUT: 3

but this code gives error: invalid initialization of non-const reference of type 'int&' from a temporary of type 'int'.

4
What are trying to do with int &x = m++; ? - ocirocir
The result of m++ is temporary object with lifetime restricted to this line. It cannot be assigned to reference - compiler message is quite clear. m++ keeps an old m value in temporary object, increments value of m, and returns temporary object with previous m value. - Alex F
@FedericoReghenzani it should work as "int &x= m; m++;" - krishnakant

4 Answers

7
votes

Post increment operator returns a temporary object with the value of m before increment. Non const lvalue references can't be bound to temporary objects. Thus, the compiler rightfully complains.

6
votes

m++ has to increase m (as a side effect), but evaluate to the original value. It does that by returning a temporary variable holding the value of m before increment.

An non-const l-value reference cannot bind to a temporary object.

You could write:

int &x = ++m;

This works because the pre–increment operator has to return the value after the increment, thus being able to evaluate to an l-value reference to m.

But I wouldn’t recommend that for clarity sake.

2
votes

You can't use post increment to assign references - it is a temporary object

2
votes

Here

int &x = m++;

you are assigning a temporary object (right side) to a reference(left side) which doesnt make any sense.

Instead,write:

int &x = ++m;