tags:

views:

124

answers:

7

Say that you are several levels deep into a recursive function. The function was originally called in main. Is there a way for you to break out of the recursion and go straight back to main without having to go through all the other functions above?

+2  A: 

You might be able to get the location off the stack and use assembler to jmp to it, but why would you want to?

Also you have to consider that when you have moved on to pastures new someone is going to have to maintain it.

graham.reeds
+8  A: 

You could use exceptions for that - either throw some suitable exception or craft your own and use it. Although using exceptions for flow control is generally not recommended this is the only reliable way here.

sharptooth
+2  A: 

In C you can use longjmp/setjmp for this, but I don't think it's safe to use this in C++ (bypasses destructors ?). You'll probably have to use exceptions.

Paul R
`longjmp`/`setjmp`? __Very bad idea__ for C++. I pretend I haven't read that.
sbi
@sbi: indeed, hence my *caveat* in the answer. There may still be specific cases where you might want to use it and it's safe to do so, e.g. simple recursive functions that do not use ctors/dtors, but in general this kind of hack should be avoided.
Paul R
A: 

Why wouldn't you want to go through all other function above?

huy
-1: this is not an answer - it should be a comment.
Paul R
+2  A: 

The question is how you got there? What kind of algorithm buries you deep into a recursion without a way of getting out of it?

Any recursive function must have a way to end the recursion, it recurses only if a condition is either true or false. When that doesn't hold, the recursion ends and the function returns instead of recursing deeper.
Why don't you just end the recursion this way, returning through all the levels?

If you're desperate, an exception is the way to go, but that's (rightly, IMO) frowned upon.

sbi
Getting out of the recursion is not the problem, getting out with the right values is. Somehow my values were getting corrupted on the way back out.
Phenom
@Phenom: And instead of analyzing and understanding the problem and fixing it you just tried to dodge it? How do you know it's not still lurking there, even though it might not occur immediately after you changed the code?
sbi
+2  A: 

Make your function so it's tail call optimizable. Then there's no "functions above" to worry about.

aspo
+1  A: 

No, you can't break from your recursion and return directly back to your main(). If your recursive function does not do other work after the recursive call you would effectively accomplish the same thing. I recommend restructuring your recursive function. A description of why you want to break from the recursion early would also be helpful.

mcdon