7

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()?

Community
  • 1
  • 1
Slava
  • 40,641
  • 1
  • 38
  • 81
  • 3
    Almost a duplicate of [this](http://stackoverflow.com/questions/2129230/cout-order-of-call-to-functions-it-prints/2129242#2129242), in short no. – CB Bailey Jul 30 '15 at 21:36
  • @MattMcNabb yes, thanks, fixed – Slava Jul 30 '15 at 22:47
  • Similar to the more complicated exampled in [Does this code from “The C++ Programming Language” 4th edition section 36.3.6 have well-defined behavior?](http://stackoverflow.com/q/27158812/1708801) but I give a lot of details in my answer which may be helpful in understanding this. There are a bunch of inter-twined issues. – Shafik Yaghmour Jul 30 '15 at 23:49

2 Answers2

6

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.

M.M
  • 130,300
  • 18
  • 171
  • 314
  • If `X`, `Y` or `Z` are function calls, they are indeterminately sequenced (in other words, can't be interleaved, as rici said) with respect to each other, not unsequenced. – Benjamin Lindley Jul 30 '15 at 21:58
  • @BenjaminLindley sorry, I always get those two mixed up – M.M Jul 30 '15 at 22:00
  • 1
    Well, you weren't completely wrong. In some cases, they would be unsequenced. For example, if they are not function calls, but instead built-in operations on primitive types. – Benjamin Lindley Jul 30 '15 at 22:03
3

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

rici
  • 201,785
  • 23
  • 193
  • 283