List the operators that require an lvalue. Why do these operators, and not the others, require an lvalue?

Question from book. Is the answer increment/decrement operator? If so, is not
a in a++ a rvalue as it takes the value of a and not the location of a?
It helps to write out what the increment and decrement operators do. I'll use the prefix increment operator in this example, but the same applies to the others.

 
++a;


Should increment the value of a by one, we could logically write it like this:

 
a = a + 1;


In this case, a is a variable, thus an lvalue since it can appear at the left side of an assignment. Now take the following example using an rvalue:

 
++2;


This uses a constant of 2, which is an rvalue. We could write this as:

 
2 = 2 + 1;


This does not make any sense. It would be weird to assign another value to a constant. This same logic applies to other rvalues as well, since this simply cannot appear at the left side of an assignment. Thus, the increment and decrement operators can only take an lvalue, since you cannot assign to an rvalue.

To answer the second part of your question, the reason a is an lvalue is because you can assign to a variable. Behind the scenes, your compiler figures out where a is stored an then writes to this location. In the type system, this is usually solved by making the type of a variable a reference, that way you can write to it in assignments, and use it like a normal value in all other operations.
Last edited on
Does this question have any context you didn't supply?

Is the answer increment/decrement operator?

Yes (and no.) For built-in types, yes. (For user-defined types, no.)

If so, is not a in a++ a rvalue as it takes the value of a and not the location of a?
a has a name, therefore a is an lvalue.

http://en.cppreference.com/w/cpp/language/value_category

Thanks a lot!
Topic archived. No new replies allowed.