2012-03-25 116 views
1

我正在編寫一個函數以遞歸方式調用自己的代碼。但我陷入了一個無限循環,因爲它似乎當函數返回它不會返回到while循環的結束括號,但它返回到int o定義的位置..任何想法,問題可能是什麼?無限遞歸C++

ErrorCode QuadTree::PartialSearchHelper(Key *key, const uint64_t QInternal, Iterator ** records,int l[], int pow) { 
    try { 
     uint64_t temp=(&indexVec[QInternal])->Firstchild; 
     uint64_t ch = (&indexVec[QInternal])->Firstchild; 
     for (int i = 0; i < pow; i++) { 
      while (!(&indexVec[temp + l[i]])->isLeaf) { 
       int o= l[i]; //it returns here after finishing recursion call!!!!!!!!! 
       PartialSearchHelper(key, temp + l[i], records, l, pow); 
      }       
      ((&indexVec[temp + l[i]]))->findPartial(key, records); 
     } 

    } catch (std::bad_alloc &e) { 
     throw (kErrorOutOfMemory); 
    } catch (ErrorCode &e) { 
     throw (e); 
    } catch (...) { 
     throw (kErrorGenericFailure); 
    } 
    return kOk; 
} 
+5

在某些情況下,這可能會導致堆棧溢出。 – 01100110 2012-03-25 15:12:42

+0

「,但它返回到int o定義的地方..」哦,不,它不。 – 2012-03-25 15:14:03

+1

爲什麼'(&indexVec [temp + 1 [i]]) - >',只要做'indexVec [temp + l [i]]。 – 2012-03-25 15:14:07

回答

8

你沒有改變,而內部的任何值,所以它只是重新啓動,同時,在較低的水平呼叫

2

每次遞歸函數調用返回準確的地方的叫法。既然你處於一個while循環中,你顯然會繼續下一次迭代。

2

在while循環中沒有計數器,沒有任何值改變。例如,讓我們非常簡單的例子:

int i = 0; 
while(i<5) 
{ 
    do.Something(); 
} 

在這一點上,「我」永遠是小於5,所以它永遠不會停止。另一方面,如果將其更改爲如下所示:

int i = 0; 
while(i<5) 
{ 
    do.Something(); 
    i=i++ 
} 

i值每次運行時都會增加1。如果while循環位於for循環中,則需要完全循環while循環才能返回for循環。嘗試在for循環中使用for循環或在while循環中插入某種計數器。

+1

嚴重的是,'我=我++'?不要介意丟失的分號,你有沒有想過當你分配和後增加相同的變量會發生什麼? – alexis 2012-09-12 20:12:15