Example of = (assignment) being right-associative
Asked Answered
J

1

0

Where would the associativity of the = assignment operator make a difference in an expression? I thought that the associativity relates to operands that share an operator, but in the case of assignment, how would that work? A few examples that (might) be relevant are:

x = 1
x + 2 = y + 3 = z + 5

Does this just mean that, in the assignments above, we would have:

y + 3 = z + 5

Done before, for example:

x + 2 = y + 3

Or what other scenarios are there where assignment associativity 'matters' ?

Jijib answered 17/1, 2021 at 21:31 Comment(3)
x + 2 = y + 3 That's not valid C, so it's not a good example. Associativity makes a difference in cases like int x, y = 0, z = 1; x = y = z;.Neel
A better example would be a = b = c + 1. You don't want it to mean a = b followed by b = c + 1.Catarrhine
In your examples, did you try them out to see if they compile?Decasyllabic
P
2

Your examples don't demonstrate anything, because associativity only comes into play when you have several operators with the same precedence (or the same operator) next to each other.

Consider x = y = 42, which sets both variables to 42.

Because of right-associativity, it's parsed as x = (y = 42), where y = ... returns the new value of y, which is 42.

This is why it works. If = was left-associative and it was parsed as (x = y) = 42, then:

  • In C it wouldn't compile at all, because x = ... returns an rvalue rather than an lvalue, and those can't be assigned to.
  • In C++, where assignments return lvalues, it would work like x = y; x = 42;, which is far from being intuitive.
Plead answered 17/1, 2021 at 21:38 Comment(1)
In C++ (x = y) = 42; would work like x=y, x=42; wouldn't it?Gradus

© 2022 - 2024 — McMap. All rights reserved.