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

2
  • In C ++a refers to a value not a variable not sure about C++ Commented May 9, 2013 at 5:29
  • Related: stackoverflow.com/questions/3690141/… Commented May 9, 2013 at 5:30

2 Answers 2

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; 
Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

"In C++, the preincrement operator yields an lvalue, whereas in C, it's an rvalue ".Why it is so?
@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 i know what is internally happening in both compiler. Is there any valid documentation?
@akhil There's the C++11 standard 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.