作者flax00298 (NI)
看板C_and_CPP
標題[問題] optimize tail recursive call
時間Fri Oct 19 02:58:54 2012
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
g++, Linux
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):
餵入的資料(Input):
預期的正確結果(Expected Output):
tail recursive call would be optimized
錯誤結果(Wrong Output):
tail recursive call is not optimized
程式碼(Code):(請善用置底文網頁, 記得排版)
54 bool insert(Node*& n , const T& t) {
55
56 if(n == NULL) {
57 n = new Node(t);
58 return true;
59 }
60 if(n->data() == t)
61 return false;
62
63 Node*& child = n->data() > t ? n->left() : n->right();
64
65 return insert(child, t);
66 }
補充說明(Supplement):
一般來說recursive call如果放在最後的話,g++應該可以優化成
iterative function,可是不知道為什麼以上的程式碼並沒有實現。
目前作過的實驗有把兩個if都comment掉,跟把child直接等於某個值。
但是g++在兩個實驗的情形之下依舊沒有作優化。請問這是為什麼?
還有如果知道更詳細關於tail recursive call 不會被優化的情形,
還請各位分享一下^^謝謝!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.229.224
→ saladim:child的值會被用到 然後必須keep住? 10/19 03:47
→ PkmX:有完整的程式和你的編譯參數嘛 我試過這種case是可以輕易被 10/19 05:17
→ PkmX:g++最佳化的 10/19 05:18
→ letoh:請問編譯時下了哪一些選項? 10/20 19:15