简体   繁体   English

“(f(x))+ g(y)”能否确保在C ++中首先调用f(x)?

[英]Does “(f(x))+g(y)” can make sure call f(x) first in C++?

And does f(x)+(g(y)) can make sure call g(y) first? 并且f(x)+(g(y))能否确保先调用g(y) I know the order in expression is undefined in many case, but in this case does parentheses work? 我知道表达式中的顺序在很多情况下是未定义的,但在这种情况下括号是否有效?

Parentheses exist to override precedence. 存在括号以覆盖优先级。 They have no effect on the order of evaluation. 它们对评估顺序没有影响。

Look ma, two lines! 看马,两行!

auto r = g(y);
f(x) + r;

This introduces the all-important sequence point between the two function calls. 这引入了两个函数调用之间最重要的序列点 There may be other ways to do it, but this way seems straightforward and obvious. 可能还有其他方法可以做到这一点,但这种方式似乎很简单明了。 Note that your parentheses do not introduce a sequence point, so aren't a solution. 请注意,您的括号不会引入序列点,因此不是解决方案。

No. Unless the + operator is redefined, things like that are evaluated left to right. 否。除非重新定义+运算符,否则从左到右评估类似的事情。 Even if you were able to influence the precedence in the operator, it wouldn't necessarily mean that f and g were evaluated in the same order. 即使您能够影响运算符的优先级,也不一定意味着fg的计算顺序相同。 If you need f to be evaluated before g , you can always do: 如果你需要在g之前评估f ,你可以随时做:

auto resultOfF = f(x);
auto resultOfG = g(x);
resultOfF + resultOfG;

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

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