Unlike the other binary operators, assignment is right associative:
int ival, jval;
ival = jval = 0; // ok: each assigned 0
Because assignment is right associative, the right-most assignment, jval = 0
, is the right-hand operand of the left-most assignment operator. Because assignment returns its left-hand operand, the result of the right-most assignment (i.e., jval
) is assigned to ival
.
Each object in a multiple assignment must have the same type as its right-hand neighbor or a type to which that neighbor can be converted (§ 4.11, p. 159):
int ival, *pval; // ival is an int; pval is a pointer to int
ival = pval = 0; // error: cannot assign the value of a pointer to an int
string s1, s2;
s1 = s2 = "OK"; // string literal "OK" converted to string
The first assignment is illegal because ival
and pval
have different types and there is no conversion from the type of pval
(int*
) to the type of ival
(int
). It is illegal even though zero is a value that can be assigned to either object.
On the other hand, the second assignment is fine. The string literal is converted to string
, and that string
is assigned to s2
. The result of that assignment is s2
, which has the same type as s1
.