1
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".

akhil
  • 732
  • 3
  • 13

2 Answers2

2

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 for pointer shifting;
  • assignment operator for assignment to pointer value (value by the address).

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;
Ze..
  • 163
  • 1
  • 10
1

Because in C++, the preincrement operator yields an lvalue, whereas in C, it's an rvalue.

  • "In C++, the preincrement operator yields an lvalue, whereas in C, it's an rvalue ".Why it is so? – akhil May 09 '13 at 05:31
  • 2
    @akhil Because the two languages are different. (This is merely a design question, and the C++ standards committee made a different decision than that of the C one). –  May 09 '13 at 05:32
  • May i know what is internally happening in both compiler. Is there any valid documentation? – akhil May 09 '13 at 05:43
  • 1
    @akhil There's the [C++11 standard](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf) from which you can select the right pieces of information. What do you mean by "what happens internally in the compiler"? It parses the source text and outputs machine code, that's what happens. –  May 09 '13 at 05:47