[英]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.考虑
x = y = 42
,它将两个变量都设置为 42。
Because of right-associativity, it's parsed as x = (y = 42)
, where y =...
returns the new value of y
, which is 42.由于右关联性,它被解析为
x = (y = 42)
,其中y =...
返回y
的新值,即 42。
This is why it works.这就是它起作用的原因。 If
=
was left-associative and it was parsed as (x = y) = 42
, then:如果
=
是左关联的并且它被解析为(x = y) = 42
,那么:
x =...
returns an rvalue rather than an lvalue, and those can't be assigned to.x =...
返回一个右值而不是左值,并且不能分配给那些。x = y; x = 42;
x = y; x = 42;
x = y; x = 42;
, which is far from being intuitive.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.