ho visto un bel casino qui, quindi ho deciso di chiarire le cose.
Soluzione 0: Statico Variabile
Si consideri il codice proposto con una modifica leggera
#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();
}
E questo è l'output:
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
Come si può vedere l'utilizzo di variabili statiche potrebbero portare ad alcuni errori terribili.
Qui avete una funzione one shot che vi causerà un grande dolore in futuro.
Inoltre l'utilizzo di variabili statiche portano a un codice illeggibile che è soggetto ad errori
Basta non farlo!
Soluzione 1: variabile passata per valore
Considerate questo codice:
#include <iostream>
using namespace std;
void fun(int i){
cout<<i<<endl;
if(i!=3) {
i++;
fun(i);
fun(i);
}
}
int main(){
fun(0);
}
Questa è l'uscita:
0
1
2
3
3
2
3
3
1
2
3
3
2
3
3
Come si può vedere l'uscita non è il numero di volte che la funzione è chiamata
Soluzione 2: variabile passata per riferimento
#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();
}
stamperà
Entry point
1
2
3
4
5
6
7
8
9
10
Questo approccio funziona anche con qualche modello ricorsivo più esotiche come questo
#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();
}
uscita:
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
È possibile aggiungere un parametro e incrementarlo durante la ricorsione. – chris
Consiglio vivamente di dare un'occhiata al mio sondaggio –