add to limit of a recursive function ?

i am coding on a program
and i have a recursive function but its stack overflows

can i add to the limit of it ?
Best way I can think of is to simply add a counter within scope of the recursion function, increment this counter every time the recursive function is called, then before the recursive function calls itself just do a check to make sure the counter has not exceeded some limit.

For Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

static int recurseMax = 10;
static int recurseCount = 0;

void recurse(){
	recurseCount++;
	printf("\n\tI am recursion number %i!", recurseCount);
	if(recurseCount >= recurseMax){
		// Recursion limit reached
		return;
	}else{
		// keep recursing
		recurse();
	}
}

int main(){
	printf("\n\n");
	printf("******************************************\n");
	printf("** Recursion limit test\n");
	printf("******************************************");

	printf("\n\nCalling recurse()...");
	recurse();

	printf("\n\n");
}
Last edited on
You need an additional depth parameter.
Not to prevent stack overflows, though. If you get a stack overflow, you have an error in your program.
Sometimes you can convert a recursive function into a loop...
Topic archived. No new replies allowed.