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?
++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 , ie an unnamed temporary value. Modifying an rvalue is not allowed in C++.
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++.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.