简体   繁体   English

=(赋值)的例子是右结合的

[英]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 ,那么:

  • In C it wouldn't compile at all, because x =... returns an rvalue rather than an lvalue, and those can't be assigned to.在 C 中它根本不会编译,因为x =...返回一个右值而不是左值,并且不能分配给那些。
  • In C++, where assignments return lvalues, it would work like x = y; x = 42;在 C++ 中,赋值返回左值,它会像x = y; x = 42; x = y; x = 42; , which is far from being intuitive. ,这远非直观。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么条件运算符会具有关联性? - Why is the conditional operator right associative? 作业右侧的评估 - Evaluation on the right side of an assignment 为什么运算符在 CShell 中是右结合的,而在 C 中是左结合的? - Why are operators right associative in CShell that are left associative in C? 有没有带有正确引力的标记的示例? - Is there an example for mark with right gravit? 指针分配和增量如何在下面的示例中工作 - how pointer assignment and increment is working in below example c复合赋值仅递增右位 - c compound assignment increment only right bits 这是在C中不是通过引用进行调用的有效示例吗? - Is this a valid example of call by reference not being true in C? 包含赋值运算符右侧数据类型的方括号 - Brackets containing a datatype on right hand side of assignment operator 为什么用指针进行转换需要在赋值的右侧进行转换 (=)? - Why does casting with a pointer require casting on the right side of the assignment (=)? 赋值语句中右边的增量表达式按哪个顺序求值? 它是未定义的吗? - In which order are the increment expressions on the right evaluated in the assignment statement? Is it undefined?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM