Search code examples
c++functionargumentsexpression-evaluation

What is the order to evaluate this and why? C++


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


Solution

  • 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 ]