1

What's the difference between the following two assignments?

#include<iostream>

using namespace std;
int main(){
    int a=10,i=0;
    ++i = a //COMPILES WITHOUT ERROR
    i++ = a //GIVES AN ERROR LVALUE NEEDED
}

Why does the second assignment produce error?

ForceBru
  • 43,482
  • 10
  • 63
  • 98
DEVESH JHA
  • 19
  • 5

2 Answers2

4

++i returns the new value of i after the incrementation. That value is an lvalue, called i in this case. Modifying i is certainly allowed.

But i++ returns the old value of i before the incrementation. That value is an rvalue, i.e. an unnamed temporary value. Modifying an rvalue is not allowed in C++.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
0

Pre-increment operation returns its argument (i) already incremented by one. The returned thing is a variable and you can assign to it.

Post-increment returns an old value of i - an rvalue, that cannot be assigned to.

See this question for implementation of operator++ in C++.

Community
  • 1
  • 1
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • @LightnessRacesinOrbit, I mean, it's garbage for the programmer as this value is not needed any more – ForceBru Oct 31 '15 at 15:53
  • In 99% of cases that is not true, otherwise the construct would not exist. Usually when people say "garbage" they mean "arbitrary/unspecified value", which certainly doesn't describe this. – Lightness Races in Orbit Oct 31 '15 at 15:55
  • @LightnessRacesinOrbit, to tell the truth, it wasn't too easy for me to choose the appropriate word in this particular case, so my choice may be wrong, I'll try to fix it now. – ForceBru Oct 31 '15 at 15:58