=(赋值)是右结合的例子 [英] Example of = (assignment) being right-associative

查看:70
本文介绍了=(赋值)是右结合的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

= 赋值运算符的结合性在哪里会对表达式产生影响?我认为结合性与共享运算符的操作数有关,但在赋值的情况下,这将如何工作?一些(可能)相关的示例是:

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

之前做过,例如:

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.

考虑 x = y = 42,它将两个变量都设置为 42.

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

由于右结合,它被解析为 x = (y = 42),其中 y = ... 返回 y<的新值/code>,即 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,则:

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

  • 在 C 中它根本无法编译,因为 x = ... 返回的是右值而不是左值,而这些不能被赋值.
  • 在 C++ 中,赋值返回左值,它会像 x = y;x = 42;,这远非直观.
  • 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.

这篇关于=(赋值)是右结合的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆