2009-08-22 64 views
5

我有一個帶有靜態變量「count」的遞歸函數。該函數遞歸遞增計數,因爲它有文件範圍,當我第二次調用foo()時,count仍然等於5.是否有一種技術在第二次調用foo()之前將count重置爲0?具有靜態變量的遞歸函數

基本上,我不希望計數有文件範圍,但我希望它通過不同的迭代保留其價值。

我能想到的一種方法是在foo()中有一個參數來初始化foo()。如foo(int count)。但還有另一種方式嗎?

#include <iostream> 

using namespace std; 

void foo() 
{ 
    static int count = 0; 

    if(count<5) 
    { 
     count++; 
     cout<<count<<endl; 
     foo(); 
    } 
    else 
    { 
     cout<<"count > 5"<<endl; 
    } 
} 

int main() 
{ 
    foo(); //increment count from 0 to 5 
    foo(); //count is already at 5 

    return 0; 
} 
+1

是否有一個特定的原因,你使用靜態計數,而不是將它作爲參數傳遞?在像這樣的遞歸函數中使用靜態變量通常被認爲是一個壞主意,正是因爲這樣的事情。 – 2009-08-22 19:33:43

+0

靜態無特殊原因。從下面的答案中,我會同意一個論點將是最好的方式去做這件事。 – Steve 2009-08-22 21:33:54

回答

19

更地道的方式是把它分成兩個功能:

void foo() { 
    foo_recursive(0); 
} 

void foo_recursive(int count) { 
    if (count < 5) { 
     count++; 
     cout << count << endl; 
     foo_recursive(count); 
    } else { 
     cout << "count > 5" << endl; 
    } 
} 

尚未要求呼叫者提供一個參數來foo(),你也並不需要一個靜態變量的好處(這我總覺得不好主意)。

+2

這可能是最好的方法。 +1除非有一些奇怪的原因,他需要一個靜態變量... – 2009-08-22 19:37:34

+2

參數默認值是有的,所以你不必做一個新的函數。我們在這裏使用C++。 void foo(int count = 0){ – Potatoswatter 2009-08-22 20:15:52

+4

默認參數應該是默認的選擇值,它們基本上位於調用者的側面。然而,這種情況下的論點是一個實現細節,應該隱藏在另一個函數的後面。你不希望調用者通過「100」作爲計數,是嗎? – 2009-08-22 20:23:47

6

把它放在別的

else 
{ 
    cout<<"count > 5"<<endl; 
    count = 0; 
} 

如果你想遞歸正確檢查出連雀的答案。

+0

這聽起來像是最好的方法。 (+1) – 2009-08-22 19:43:56

4

而不是使用靜態變量,只需將count作爲參數。

void foo(int count) { 
    if (count < 5) { 
     count++; 
     cout << count << endl; 
     foo(count); 
    } else { 
     cout << "count > 5" << endl; 
    } 
} 

int main() { 
    foo(0); 
    foo(0); 
} 

靜態變量和遞歸通常不會在一起。

0

您可以將foo更改爲接受布爾變量,這意味着重置與否。

void foo() { 
    foo(false); 
} 

void foo(int b) 
{ 
    static int count = 0; 

    if(b) { count = 0 }; 

    ... 
} 

如前所述,調用foo()或foo(true),如果您想重置它。

0

您可以進行功能的自動復位是這樣的:

void foo() { 
    if (count >= 5) { 
    cout<<"count >= 5"<<endl; 
    count = 0; 
    return; 
    } 

    cout<<++count<<endl; 

    foo(); 
} 

保存樣板代碼。

0
void foo() { 
    ... 
    if (count > 0) count--; // you can decrease it at then end of foo() 
} 
1

這個怎麼樣

count = (count+1)%5 
0

無需申報有兩項功能或使用靜態變量。你可以使用默認參數。

// Use Default arguments 
void foo(int count = 0); 

void foo(int count) 
{ 
    if(count<5) 
    { 
     count++; 
     cout<<count<<endl; 
     foo(count); 
    } 
    else 
    { 
     cout<<"count > 5"<<endl; 
    } 
} 

int main() 
{ 
    foo(); // by default argument =0 
    foo(); // by default argument =0 

    return 0; 
}