akhil
akhil

Reputation: 732

Error in C compiler but not in c++ compiler

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

Upvotes: 1

Views: 231

Answers (2)

Ze..
Ze..

Reputation: 163

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;

Upvotes: 2

user529758
user529758

Reputation:

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

Upvotes: 1

Related Questions