r/C_Programming • u/choosen_one007 • Oct 15 '26
Question Why are assignment expressions lvalues?
I was reading up about lvalues and understand them now as something that resolves to an address(memory location) in the program. So a variable x is an lvalue (because it is mapped to some address on the stack) and similarly *x , x[i], strings are all lvalues. But if this is the case why is an expression a = b , not an lvalue? Here the expression would assign b to a and then return a as evident in assignments like so: int c = a = b. (I know that the equals sign is right associative and hence this would get resolved as c = (a = b), but that doesn't really invalidate the fact that a = b resolves to an address in the program?)
View all comments
Show parent comment
6
u/nzconstructionlawyer Oct 15 '26
I disagree. I think the best way of thinking about lvalues and rvalues is as locations vs values. An lvalue is an identifiable place: a, or a.b, or a.b.c[d]. An rvalue is just an anonymous value, like 1. Essentially, an lvalue is a memory location, and an rvalue is a temporary stored in a register.
It isn't right to say that an rvalue is anything because lvalues implicitly convert because that disregards that the conversion does do something: it's a load to a register. If a is stored on the stack then converting it to an rvalue means loading a into a temporary register. So "a + 1" means "load a from memory into a register, then generate a value of 1 in a register, then compute in a register the sum of those two registers". Assignment is, conceptually, storing a value into memory.
Then it is immediately obvious why you the result of an assignment is an rvalue: after you store the value into memory, you still have the register with the value, so you can store it into another register. "a = (b = v);" means "store the value v into b then into a".
What would it mean to assign to "a = v"? If it were an lvalue it would have to be just a again. So "(a = v) = w;" would have to mean "store v into a then store w into a" which is totally pointless, just write a = w.
If you write a naive compiler then this is exactly what lvalues and rvalues are. Of course in an optimising compiler those "memory locations" may actually be (permanently or cached) in registers and "stores" and "loads" to them are actually just register copies, but ultimately it amounts to the same thing: there are anonymous values and there are identified places where data is stored long term: rvalues and lvalues. "Values and places" is a much better terminology used by other languages.
That's why *p is always an lvalue (dereferencing obtains a place from an address value), &a is always an rvalue (addressof always obtains the address of a memory location), and &v makes no sense where v is an rvalue (values dont have locations - what is the address of a register?).