today I performed an experiment with a "recursive" function, my code is below. when I run the program I get a segmentation fault, I was wondering why I got it (besides calling itself)?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
usingnamespace std;
int funct(int x){return funct(x);}
int main()
{
cout << funct(3) << endl;
return 0;
}
thanks
p.s: the tags for code and other things for some reason don't work, so I had to do it manually. Has anyone else had this problem?
It's easy to forget the base case of a recursive function as you have done here. For that reason, and the make the base case and recursive cases clear, I always code recursive functions like this:
1 2 3 4 5 6 7 8
someFunc()
{
if (base_case_condition) {
do the base case and return;
} else {
do the recursive case;
}
}
By coding the base case first, you force yourself to remember it.