0
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

Stack Danny
  • 5,198
  • 1
  • 15
  • 42

2 Answers2

1
int &c = a++; 

You get the error because a++ results in rvalue expression whose reference you cannot take.

For more info on lvalue,rvalue

kiran Biradar
  • 12,116
  • 3
  • 14
  • 35
0

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.

Markus Mayr
  • 3,568
  • 16
  • 38