ARBY ARBY - 3 months ago 7
C Question

Please clarify the concept of lvalue and rvalue here

I have the program given below

#include<stdio.h>
int main()
{
int i=5;
(++(++i));
}


This program compiles fine in c++ but not in c. I couldn't truly understand either. But I've tried reading and searching and found that this is because preincrement operator returns rvalue in c and lvalue in c++.

If I change
(++(++i))
to
(++(i++))
then compilation fails in both in c and c++ because post-increment always returns rvalue.

Even after some reading, I don't get a clear picture of what exactly lvalue and rvalue mean here. Can somebody explain me in layman terms what are these?

Answer

In c the postfix or prefix ++ operators require that the operand is a modifiable lvalue. Both operators perform an lvalue conversion, so the object is no longer an lvalue.

C++ also requires that the operand of the prefix ++ operator is a modifiable lvalue, but the result of the prefix ++ operator is an lvalue. This is not the case for the postfix ++ operator.

Therefore (++(++i)); compiles as the second operation gets an lvalue, but (++(i++)) doesn't.