Let’s say we have a simple recursion like.
int x(int a){
if(a<10)
x(a+1);
else
!STOP!
b++;
return b;
}
Globaly:
int b=0;
In main we could have something like this:
int p=x(1);
Is there any way to stop the recursion so that the p will be 0, this means that “b++” will never be executed.
I’ll be grateful if you could tell me some expresion to put instead of the !STOP!
But, I don’t want anything like this, I just want to stop the recursion, like break; does in a while() loop…:
int ok=0;
int x(int a){
if(a<10)
x(a+1);
else
ok=1;
if(ok==0)
b++;
return b;
}
If there’s anything unclear about the question, just ask.
Why wouldn’t you do this?
The thing is, though, you’re modifying a global in a recursive routine, which is not especially threadsafe and pretty sloppy. You’re returning a value that is always ignored except by the top level caller. You’re also doing something that is better off being done in a loop (but I assume that your actual case is bigger than this, or you’re a student).
You can’t really “break” the recursion – returning unwinds well enough. In oldey-timey C you might use setjmp/longjmp (and all its perils – in other words, DON’T), and in C++ you might use try/catch/throw, which will unwind the stack as well.