Search code examples
crvaluelvalue

Lvalues and Rvalues in a multi-variable assignment


In the following:

int a, b, c;
a = b = c = 4;

How are the r-values and l-values classified? My guess is, from a parsing perspective, we would start off with R-to-L precedence on equals/assignment, so it would be:

c (lv) = 4 (rv)

Now c has the value 4 and b becomes the lvalue:

b (lv) = c/4 (rv)

And again:

a (lv) = b/4

So, perhaps it would look something like:

a (lv) = (
    b (lv) = (
        c (lv) = 4 (rv) // start here
    ) (rv)
) (rv)

Is that more-or-less a correct understanding of assignment, lvalues, and rvalues?


Solution

  • As you know, an lvalue is something that has a location, and that can therefore appear on the left-hand sign of an assignment operator.

    In

    a = b = c = 4;
    

    I would say that a, b, and c are all lvalues, and that 4 is an rvalue.

    If you need the value of something, and the something is an rvalue, you're done: you have a value. If the something is an lvalue, you fetch a value from it, and that's the value you need.

    If you're trying to store a value into something, and the something is an lvalue, you're in luck: you can store it. But if the something is an rvalue, you can't, it's an error.

    When you say

    a = b = c = 4;
    

    the first assignment that happens is indeed of 4 to c, and for this to work it's obviously important that c be an lvalue. But when it comes time to do the second assignment, I don't think of that as reinterpreting c as an rvalue: the value to be stored in b is the same value that was just stored in c. (Formally: "In c = 4, the resulting value is the value that was stored into c, and is an rvalue.")