簡體   English   中英

Function 調用的優先級/Function 調用的優先級

[英]Precedence of Function Calls/Priority of Function Calls

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;
Alpha answer=q(&a)+p(&a)行中交換 Function 調用導致answer=50 a=20 ,這可以通過說函數調用優先級從左到右來證明,但是當我們將行 alpha 更改為answer=p(&a)+a+q(&a); output 是answer=70 a=30
function 在哪里調用適合優先級表? foo()+1010+foo是等效的語句嗎?

任何表達式的任何部分的評估順序,包括 function arguments 的評估順序未指定(下面列出了一些例外情況)。 編譯器可以按任何順序計算操作數和其他子表達式,並且可以在再次計算同一表達式時選擇另一個順序。

C++ 中沒有從左到右或從右到左求值的概念。 不要將這與運算符的從左到右和從右到左的結合性相混淆:表達式 a() + b() + c() 被解析為 (a() + b()) + c( ) 由於 operator+ 的從左到右的關聯性,但 function 對 c 的調用可能在運行時首先、最后或在 a() 或 b() 之間進行評估

更詳細的解釋見報價來源: https://en.cppreference.com/w/cpp/language/eval_order

所以,在你的情況下

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

第一個要執行的 function 可能是pq

在這里,這條規則也適用:

  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).

這意味着對pq的調用,即使是內聯的,也不能以允許它們交錯的方式進行優化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM