0
int foo(int a, int& b, int c) {
    int temp = a;
    a = b;
    b = c;
    c = temp;
    return a - b;
}

int main() {


**foo(foo(a, b, c), b, foo(a, b, foo(a, b, c)));**


return 0;
}

which foo function call is evaluated first and why? the code i posted was simplified so there's no need to trace it. thank you

Christophe
  • 68,716
  • 7
  • 72
  • 138
csguy
  • 1,354
  • 2
  • 17
  • 37

1 Answers1

2

Assuming that the ** are typos and not syntax errors, and using the following naming:

 (A)      (B)          (C)       (D) 
foo ( foo(a, b, c), b, foo(a, b, foo(a, b, c)))

the follwing is true:

  • (D) is evaluated before (C) because the parameter value is required for calling (C).
  • (A) is evaluated after (B), and (C) (and therefore (D) )

More cannot be said because, the C++ standard lets the ordering of the parameter evaluation to the compiler :

5.2.2/4: When a function is called, each parameter shall be initialized with its corresponding argument. [Note: Such initializations are indeterminately sequenced with respect to each other — end note ]

Christophe
  • 68,716
  • 7
  • 72
  • 138
  • I meant to point out the part of the code with ** and thank you, I think I understand now – csguy Nov 19 '16 at 19:49
  • It's UB because `b` is modified. – Richard Critten Nov 20 '16 at 00:20
  • Indeed, there are 4 unsequenced side-effects on the same variable, which is UB. But prior being able to make this statement, one first have to identify that they are not sequenced (i.e. no defined order), which was precisely the goal this question. – Christophe Nov 20 '16 at 01:12
  • @Christophe but if UB is not mentioned in an answer the OP may believe that such expressions are sensible. – Richard Critten Nov 20 '16 at 10:46
  • @RichardCritten the question looks more like a homework question aiming to check if student recalled the unsesuenced evaluation, rather than a real life question, where there could be a risk of putting this in real code, so I limit myself to answer the question. – Christophe Nov 20 '16 at 11:38
  • Yes it was a code tracing problem and i just took out a part that i had trouble with – csguy Nov 21 '16 at 08:22