r/C_Programming • • 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?)

11 Upvotes

35 comments sorted by

View all comments

19

u/MyNameIsHaines Oct 15 '26

Assigning something to (a = b) would be nonsensical no?

9

u/tharold Oct 15 '26

Gnu C allows the ternary operator to evaluate to an lval, as a language extension. So you can do (flag?a:b)=42; Which is occasionally useful.

2

u/Vincenzo__ Oct 19 '26

This is disgusting and I love it

1

u/choosen_one007 Oct 15 '26

Isnt this a very common pattern in C code? For example in linux: https://github.com/torvalds/linux/blob/master/fs/proc/stat.c#L57

25

u/Eidolon_2003 Oct 15 '26

a = b = c groups like a = (b = c), not (a = b) = c if that makes sense

4

u/type_111 Oct 15 '26

AKA right-to-left associativity.

6

u/Scolmann Oct 15 '26

Yeah but (a = b) = c; doesn't make much sense to me
It looks like you wouldn't assign b's value, you just assign to immediately reassign

1

u/flatfinger Oct 15 '26

I can see a couple of use cases for such assignments:

  1. Multiple stores to a volatile object may have distinct effects. For example, many chips that have a serial port, storing 'H' and then 'i' to an associated volatile object when two buffer slots are available would output "Hi". Maybe not common enough to be worth bothering with in the language, but occasionally useful.
  2. A fair number of tasks involve constructs like dest = (dest & mask) ^ flips; and being able to do (dest &= mask) ^+ flips; could avoid the need to specify the destination twice. It might be better, though, to have an explicit ternary "cookie cutter" operator.