Question

hello I am learning basics of C programming language, recently i have studied about post and pre increment/decrement operators and also about lvalue and rvalue, the following program shows an error, lvalue required, according to me it should give a value of 6, Can anyone please explain why?

int main(){
  int x = 8, y;
  y = --x--;
  printf("y=%d",y);
  return 0;
}

Please explain, why is it so?

Was it helpful?

Solution

Well, let's see what is happening in --x--. At first, post-decrement executes: --(x--). (x--) = 7. After that result of this operation is placed to the original structure: --7 - doesn't make sense - thus you get lvalue required error

OTHER TIPS

The statement y = --x--; will give you the following error on compilation in C. lvalue required. This is because the post decrement operator -- will return an rvalue after operating on the variable x. So there are no lvalue to perform the pre decrement operator -- afterwards.

But this is one point where C and C++ differs. In C the following statement will also give you the same error lvalue required.

y = (--x)--;

But in C++ the statement y = (--x)--; will compile fine and the value of y is 7. Because unlike C, C++ returns an lvalue after performing the pre decrement operator on variable x.

L Value is left operand of assignment operator which should refer to memory location.As explained by @Pavel your Lvalue is becoming a value not object so you are getting error.

--x means x = x-1 but in your case it is becoming --7 which will be equivalent to 7 =7-1 which is definitely not valid expression.

Other than this more than one operation on same variable without any sequence point in between, results undefined behaviour.

C order of operations specifies that postfix operators have precedence over the prefix operators. The -- postfix operator returns the current value (an rvalue) of the operand and then decrements the operand. Then the prefix decrement operator would be applied...but the decrement/increment operators need lvalue operands since they by definition modify their operands. So, as the compiler says, an lvalue is required.

You should not use it at a time because you will not understand the behavior of compiler. So, you need to guide your code so that they will forced to do what you like.

Now come to your point. If you want to decrease the value by one you can use a-- or --a. They will do the same. If a = 5 and you use b=a-- you will get b = 5 and a = 4 where if you use b=--a you will get b = 4 and a = 4 in --a the value is assigned immediately and in a-- value will be assigned after statement is complete. Hope you are clear.

L value required error shown when it doesn't find any suitable variable where it can be assigned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top