简体   繁体   English

嵌套函数调用评估顺序

[英]Nested function calls order of evaluation

It's well-known that the order of evaluation of a function's arguments in unspecified and can differ between different compilers. 众所周知,函数参数的评估顺序未指定,并且可能因不同的编译器而不同。

What doesn't seem so clear is whether function calls can be interleaved, in the following sense: 似乎不太清楚的是函数调用是否可以交错,具体如下:

f(g(h()), i(j()))

Let's assume the compiler chooses to evaluate f's first parameter first. 让我们假设编译器首先选择评估f的第一个参数。 Is the compiler free to call j between calling h and g ? 编译器是否可以在调用hg之间调用j I believe so, but I don't know where to find confirmation in the Standard. 我相信,但我不知道在标准中哪里可以找到确认。

The evaluation order is unspecified - see section 5.2.2/8 of the Standard: 评估订单未指定 - 参见标准第5.2.2 / 8节:

The order of evaluation of arguments is unspecified. 参数的评估顺序未指定。 All side effects of argument expression evaluations take effect before the function is entered. 参数表达式求值的所有副作用在输入函数之前生效。

I don't know what the standard says, but I think that if it matters to you, then you should probably re-arrange the code so that you know what's going to happen in which order (temp variables are your friends). 我不知道标准是什么,但我认为如果对你很重要,那么你应该重新安排代码,以便你知道将以什么顺序发生什么(临时变量是你的朋友)。 Even if you figure out what the standard says, AND if we assume that your compiler implements that correctly, you're still leaving a maintenance time bomb, because your successors WON'T know everything you do. 即使你弄明白标准是什么,如果我们假设你的编译器正确地实现了这一点,那么你仍然会留下维护定时炸弹,因为你的继任者不会知道你所做的一切。

The evaluation order is not specified by the standart. 标准未指定评估顺序。 It depends only on your compiler. 它仅取决于您的编译器。

If the functions you're using in the same expression are somehow related (one affects the results of the other), so different order of calls give different results, then refrain of using nested functions in expressions. 如果您在同一表达式中使用的函数以某种方式相关(一个影响另一个的结果),那么不同的调用顺序会给出不同的结果,然后在表达式中避免使用嵌套函数。

I do it as good practice, exactly because, as the other said, the calling order is undefined (you could have even interlaced execution, if the optimizer thought it will be more optimal). 我这样做是好的做法,正是因为,正如另一个所说,调用顺序是未定义的(如果优化器认为它更优化,你甚至可以进行隔行执行)。

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

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