int a=5; ++a=a; Please find the above code segment. The code is ok for the c++(g++) compiler but shows error while using c (gcc) compiler. May I know the reason for this? The error in c compiler is "lvalue required as left operand of assignment".
int a=5; ++a=a; Please find the above code segment. The code is ok for the c++(g++) compiler but shows error while using c (gcc) compiler. May I know the reason for this? The error in c compiler is "lvalue required as left operand of assignment".
There is operator overloading in C++ (and you can overload pre-increment also), so to achieve some additional goals pre-increment operator returns lvalue in C++.
For example:
Your class may implement some pointer functionality and may need:
Pre-increment may be useful in this case.
Abstract code example:
class MyIntPtr { int *val; ... public: MyIntPtr(int *p) { ... }; MyIntPtr &operator++() { ++val; return *this; }; void operator=(int i) { *val = i; } ... }; ... int array[10]; MyIntPtr ptr(array); for(int i = 0; i < sizeof array; ++i) ++ptr = i; Because in C++, the preincrement operator yields an lvalue, whereas in C, it's an rvalue.