简体   繁体   English

c++ 中运算符的关联性和求值顺序有什么区别

[英]what is the difference between operators associativity and order of evaluation in c++

What is the difference between operators associativity and order of evaluation?运算符的结合性和求值顺序有什么区别?

I have expected that operator associativity is a precedence of operators which in the same group and have the same precedence, but I cannot understand the difference between operators associativity and order of evaluation我期望运算符关联性是同一组中具有相同优先级的运算符的优先级,但我无法理解运算符关联性和评估顺序之间的区别

Associativity informs the order of evaluation of the components of an expression, but it does not entirely define it.关联性告知表达式的组件的评估顺序,但它并没有完全定义它。

Consider this expression: a + b + c .考虑这个表达式: a + b + c Associativity of + is left-to-right, so we know that this is conceptually equivalent to ((a + b) + c) . +的结合性是从左到右的,所以我们知道这在概念上等同于((a + b) + c) What this means is that the expression a + b gets evaluated before the addition of that result to c .这意味着表达式a + b在将结果添加到c之前得到评估。 That informs the order of evaluation.这通知了评估的顺序。

But this does not entirely define ordering.但这并不能完全定义排序。 That it, it does not mean that a or b gets evaluated before c .它并不意味着abc之前得到评估。 It is entirely possible for a compiler to evaluate c first, then a and then b , then + ing a and b , and finally + ing that to the result of c .编译器完全有可能首先评估c ,然后ab ,然后+ ing ab ,最后+ ing 得到c的结果。 Indeed, in C++14, it is possible for a compiler to partially evaluate c , then evaluate part of a , then some of b , then some of c etc. That all depends on how complex a , b , and c are.实际上,在 C++14 中,编译器可以部分评估c ,然后评估a一部分,然后评估b的一部分,然后评估c的一部分等等。这完全取决于abc的复杂程度。

This is particularly important if one of these is a function call: a(x + y, z) + b + c .如果其中一个是 function 调用,这一点尤为重要: a(x + y, z) + b + c The compiler can evaluate x , then c , then z , then y , then b , then x + y , then evaluate a , then call the result of that evaluation, then adding that to b , then adding that to c .编译器可以评估x ,然后c ,然后是z ,然后y ,然后是b ,然后是x + y ,然后评估a ,然后调用该评估的结果,然后将其添加到b ,然后将其添加到c

In C++, "associativity" refers to the direction in which an operator is applied to its operands, while "order of evaluation" refers to the order in which operands are evaluated.在 C++ 中,“关联性”是指运算符应用于其操作数的方向,而“求值顺序”是指操作数求值的顺序。 For example, the addition operator (+) has left-to-right associativity, meaning multiple additions in an expression are evaluated from left to right.例如,加法运算符 (+) 具有从左到右的结合性,这意味着表达式中的多个加法是从左到右计算的。 However, the order of evaluation is not guaranteed to be predictable, and can affect the result of an expression with side effects.但是,评估的顺序不能保证是可预测的,并且会影响具有副作用的表达式的结果。 Understanding these concepts is important for writing correct and predictable code.理解这些概念对于编写正确且可预测的代码很重要。

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

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