In C++, pre-increment (or pre-decrement) can be used as l-value, but post-increment (or post-decrement) can not be used as l-value.
For example, following program prints a = 20 (++a is used as l-value)
a = 20
The above program works whereas the following program fails in compilation with error “non-lvalue in assignment” (a++ is used as l-value)
prog.cpp: In function 'int main()': prog.cpp:6:5: error: lvalue required as left operand of assignment a++ = 20; // error ^
How ++a is different from a++ as lvalue?
It is because
++a returns an lvalue, which is basically a reference to the variable to which we can further assign — just like an ordinary variable. It could also be assigned to a reference as follows:
int &ref = ++a; // valid int &ref = a++; // invalid
Whereas if you recall how
a++ works, it doesn’t immediately increment the value it holds. For brevity, you can think of it as getting incremented in the next statement. So what basically happens is that
a++ returns an rvalue, which is basically just a value like the value of an expression which is not stored. You can think of
a++ = 20; as follows after being processed:
int a = 10; // On compilation, a++ is replaced by the value of a which is an rvalue: 10 = 20; // Invalid // Value of a is incremented a = a + 1;
That should help to understand why
a++ = 20; won’t work.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Difference between Sentinel and Counter Controlled Loop in C
- Why do we need reference variables if we have pointers
- What are the differences between C and Embedded C?
- Similarities and Difference between Java and C++
- Macros and its types in C/C++
- How to find index of a given element in a Vector in C++
- Introduction to Complex Objects and Composition
- Draw a smiley face using Graphics in C language
- NULL undeclared error in C/C++ and how to resolve it
- Draw a Chess Board using Graphics Programming in C
- Which will be faster while(1) or while(2)?
- what happens when you don't free memory after using malloc()
- std::remove_const in C++ with Examples
- Finding Median of unsorted Array in linear time using C++ STL
- Average of Cubes of first N natural numbers
Improved By : SangeethSudheer