Precedence of Function Calls/Priority of Function Calls

755 Views Asked by At
int p(int *ptrP){
    *ptrP=20;
    return *ptrP;
}

int q(int *ptrQ){
    *ptrQ=30;
    return *ptrQ;
}

int main(){
    int answer=0,a=10;
    answer=p(&a)+q(&a);      // line Alpha,for discussions sake 
    printf(" answer=%d a=%d ",answer,a ); 
}

Output:answer=50 a=30;
Swaping the Function calls in line Alpha answer=q(&a)+p(&a) result in answer=50 a=20, this can be justified by saying that fucntion call precedence is left to right, but when we change line alpha to answer=p(&a)+a+q(&a); the output is answer=70 a=30.
Where does function calling fit-in the precedence table? Are foo()+10 and 10+foo equivalent statements?

1

There are 1 best solutions below

2
On

Order of evaluation of any part of any expression, including order of evaluation of function arguments is unspecified (with some exceptions listed below). The compiler can evaluate operands and other subexpressions in any order, and may choose another order when the same expression is evaluated again.

There is no concept of left-to-right or right-to-left evaluation in C++. This is not to be confused with left-to-right and right-to-left associativity of operators: the expression a() + b() + c() is parsed as (a() + b()) + c() due to left-to-right associativity of operator+, but the function call to c may be evaluated first, last, or between a() or b() at run time

For a more detailed explanation see the source of the quotation: https://en.cppreference.com/w/cpp/language/eval_order

So, in your case

answer=p(&a)+q(&a);

the first function to execute may be p or q.

Here this rule also applies:

  1. A function call that is not sequenced before or sequenced after another function call is indeterminately sequenced (the program must behave as if the CPU instructions that constitute different function calls were not interleaved, even if the functions were inlined).

which means that the calls to p and q, even when inlined, cannot be optimized in a way that permits their interleaving.