Function interleaving in pre C++17

gez*_*eza 3 c++ language-lawyer c++11 c++14 c++17

Look at this simple function call:

f(a(), b());
Run Code Online (Sandbox Code Playgroud)

According to the standard, call order of a() and b() is unspecified. C++17 has the additional rule which doesn't allow a() and b() to be interleaved. Before C++17, there was no such rule, as far as I know.

Now, look at this simple code:

int v = 0;

int fn() {
    int t = v+1;
    v = t;
    return 0;
}

void foo(int, int) { }

int main() {
    foo(fn(), fn());
}
Run Code Online (Sandbox Code Playgroud)

With C++17 rules, v surely will have the value of 2 after the call of foo. But, it makes me wonder, with pre-C++17, is the same guaranteed? Or could it be that v ends up 1? Does it make a difference, if instead of int t = v+1; v = t;, we just have v++?

P.W*_*P.W 6

在以前的版本中,函数调用也不允许交织。

引用C ++ 11最终草案(n3337)

1.9程序执行[介绍执行]
...

15。...调用函数时(无论函数是否为内联),与任何参数表达式或指定所调用函数的后缀表达式关联的每个值计算和副作用都将在执行每个表达式或语句之前进行排序被调用函数的主体。[注意:与不同参数表达式关联的值计算和副作用是无序列的。[-结束注释]相对于被调用函数9的执行,不确定地对调用函数中未按特定顺序排序的调用函数中的每个评估(包括其他函数调用)进行排序。


9)换句话说,函数执行不会相互交错

在C ++ 14版本的最终草案中也可以找到类似的措辞。

  • OP使函数与* expressions *混淆,后者可能在C ++ 14中交错。那就是说,如果您有一个复合表达式,例如f(a()+ b(),c()+ d()),则执行顺序可能是a(),然后是c(),然后是“ b()”,然后是“ d()”,依此类推。 (3认同)