Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of evaluation of f(g(), h()) in C++

This is sort of a follow-up to Could a C++ implementation, in theory, parallelise the evaluation of two function arguments?

Suppose I have the following C++11 program:

#include <cstdio>
using std::printf;
int g() { printf("1\n"); printf("3\n"); return 2; }
int h() { printf("2\n"); printf("4\n"); return 3; }
void f(int a, int b) { printf("%i\n", a+b); }
int main() { f(g(), h()); }

Certainly the following outputs are observable:

1 3 2 4 5
2 4 1 3 5

What about 1 2 3 4 5?

(As far as I can tell, the only constraints are that 1 is sequenced before 3, 2 is sequenced before 4, and both 3 and 4 are sequenced before 5.)

like image 562
tmyklebu Avatar asked Feb 18 '23 11:02

tmyklebu


1 Answers

C++03 did normatively say that function invocations do not interleave. C++11 says normatively that

Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function.

Both are sufficient to disallow this.

like image 105
Johannes Schaub - litb Avatar answered Feb 28 '23 10:02

Johannes Schaub - litb