How does multiple assignment (a = b) = c syntax work? [closed]

The assignment expression a = b is not an lvalue in C, but it is in C++:

  • C11, 6.5.14 (Assignment operators):

    An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment, but is not an lvalue.

  • C++14, 5.18 [expr.ass] (Assignment and compound assignment operators):

    The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand.

In the evolution of C++ from C, several expressions were made “lvalue-aware”, as it were, because lvalues are much more important in C++ than in C. In C, everything is trivial (trivially copyable and trivially destructible, all in the words of C++), so lvalue-to-rvalue conversions (or “lvalue conversions”, as C calls them) aren’t painful. In C++, copying and destruction are non-trivial concepts, and by making expressions preserve lvalue-ness, a lot of copying and destructing can be avoided that was never necessary to begin with.

Another example is the conditional expression (a ? b : c), which is not an lvalue in C, but can be a lvalue in C++.

Another interesting artefact of this language evolution is that C has four well-defined storage durations (automatic, static, thread-local, dynamic), but in C++ this becomes more muddled, since temporary objects are a non-trivial concept in C++ that almost calls for its own storage duration. (E.g. Clang internally has a fifth, “full expression” storage duration.) Temporaries are of course the result of lvalue-to-rvalue conversion, so by avoiding the conversion, there’s one less thing to worry about.

(Please note that all of this discussion only applies to the respective core language expressions. C++ also has the separate, unrelated feature of operator overloading, which produces function call expressions, which have all the usual semantics of function calls and have nothing to do with operators except for the syntax. For example, you can define an overloaded operator= that returns a prvalue or void if you so wish.)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)