我看到这里很乱,所以我决定把这些东西清理干净。
解决方案 0:静态变量
考虑稍作修改后提出的代码
#include<iostream>
using namespace std;
void fun()
{
static int count=1;
count++;
cout << "fun() is called " << count << " times" << endl;
if(count<=10)
{
fun();
}
}
int main()
{
cout << "first call" << endl;
fun();
cout << "second call" << endl;
fun();
cout << "third call" << endl;
fun();
}
导致此输出:
first call
fun() is called 2 times
fun() is called 3 times
fun() is called 4 times
fun() is called 5 times
fun() is called 6 times
fun() is called 7 times
fun() is called 8 times
fun() is called 9 times
fun() is called 10 times
fun() is called 11 times
second call
fun() is called 12 times
third call
fun() is called 13 times
如您所见,使用静态变量可能会导致一些意外行为。
这是一个一次性的功能,将来会让您感到头疼。此外,静态变量的使用会导致代码不可读,容易出错
只是不要这样做!
解决方案1:按值传递的变量
考虑这段代码:
#include <iostream>
using namespace std;
void fun(int i){
cout<<i<<endl;
if(i!=3) {
i++;
fun(i);
fun(i);
}
}
int main(){
fun(0);
}
这是输出:
0
1
2
3
3
2
3
3
1
2
3
3
2
3
3
如您所见,输出不是调用函数的次数
解决方案 2:通过引用传递的变量
#include <iostream>
using namespace std;
void fun(int& x){
if(x>=10)
return;
++x;
cout << x << endl;
fun(x);
}
void funEntry(){
int x = 0;
cout << "Entry point" << endl;
fun(x);
}
int main(){
funEntry();
funEntry();
}
将打印
Entry point
1
2
3
4
5
6
7
8
9
10
这种方法也适用于像这样的一些更奇特的递归模式
#include <iostream>
using namespace std;
void fun(int i, int& x){
if(i>=4)
return;
++x;
cout << i << " " << x << endl;
fun(i+1,x);
fun(i+2,x);
}
void funEntry(){
int x = 0;
cout << "Entry point" << endl;
fun(0,x);
}
int main(){
funEntry();
funEntry();
}
输出:
Entry point
0 1
1 2
2 3
3 4
3 5
2 6
3 7
Entry point
0 1
1 2
2 3
3 4
3 5
2 6
3 7