Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of evaluation in chain invocation in C++

Let's say we have class A:

class A {
public:
    A& func1( int ) { return *this; }
    A& func2( int ) { return *this; }
};

and 2 standlone functions:

int func3();
int func4();

now in this code:

A a;
a.func1( func3() ).func2( func4() );

is order of evaluation of functions func3() and func4() defined?

According to this answer Undefined behavior and sequence points one of the sequence points are:

  • at a function call (whether or not the function is inline), after the evaluation of all function arguments (if any) which takes place before execution of any expressions or statements in the function body (§1.9/17).

So does "evaluation of all function arguments" mean, func3() has to be called before func4() as evaluation of func1() arguments has to happen before call of func2()?

like image 557
Slava Avatar asked Jul 30 '15 21:07

Slava


2 Answers

The gist of it is that in a function call, X(Y, Z) ; evaluation of all of X, Y, Z are indeterminately sequenced with respect to each other. The only sequencing is that Y and Z are sequenced-before the call to the function which X evaluated to.

Suppose we have:

typedef void (*fptr)(int, double);
fptr a();
int b();
double c();

a()(b(), c());

The three functions a, b, c may be called in any order. Of course this all applies recursively to any sub-expressions.

like image 106
M.M Avatar answered Oct 13 '22 09:10

M.M


No, func3 and func4 may be evaluated in either order (but not interleaved).

like image 37
rici Avatar answered Oct 13 '22 08:10

rici