int main()
{
int a = 10;
int &b = ++a; // this line works fine
int &c = a++; // results in error
}
can someone please explain me reason for this
int main()
{
int a = 10;
int &b = ++a; // this line works fine
int &c = a++; // results in error
}
can someone please explain me reason for this
int &c = a++;
You get the error because a++
results in rvalue
expression whose reference you cannot take.
In non-technical terms, it is forbidden, to take a (non-const) reference to a temporary.
The expression ++a
does not generate a temporary. It modifies itself and returns a reference to itself.
The expression a++
on the other hand, creates a copy of itself, then modifies itself, then returns the copy. That copy is a temporary.