2013-12-08 72 views
1

編譯器是否有可能在這種情況下識別尾遞歸?複雜的尾遞歸案例

void f(int x) { 
    if (x == 1) { 
     /* do_1... */ 
    } 
    else if (x == 2) { 
     /* do_2... */ 
    } 
    else if (x == 3) { // here, we want do_2 and do_3; the order doesn't matter 
     /* do_3... */ 
     f(2); // this should be tail recursive 
    } 
    else if (x == 4) { 
     /* do_4... */ 
    } 
} 

會放置return;f(2);幫助編譯器將其識別爲一個尾遞歸的情況下?

+1

你有沒有試過看編譯器的輸出?您的問題的答案非常特定於編譯器,包括版本,優化標誌等。 –

+0

您不應該依賴優化尾遞歸的C++編譯器。如果正確的行爲取決於不炸掉堆棧,則應該消除遞歸。 –

+0

同時檢查棧幀重用是否發生也是一種選擇! :) – ScarletAmaranth

回答

0

一個識別tail-call優化機會的編譯器在該特定用例中應該沒有問題的識別。