简体   繁体   中英

Example of = (assignment) being right-associative

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'?

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; x = y; x = 42; , which is far from being intuitive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM