Exiting a recursive function at the topmost level in C ++

Say you are several levels deep in a recursive function. Initially, the function was mostly called. Is there a way to break out of recursion and go straight back to the main one without going through all the other functions above?

+2


a source to share


7 replies


You can use exceptions for this - either throw some suitable exception or create your own and use it. While using exceptions for flow control is generally not recommended, it is the only reliable way here.



+9


a source


In C you can use longjmp

/ setjmp

to do this, but I don't think it's safe to use it in C ++ (bypass destructors?). You will probably have to use exceptions.



+4


a source


You might be able to set the location from the stack and use assembler for the jmp, but why would you want?

Also, you should consider that when you switched to pastures, the new person will have to support him.

+2


a source


The question is, how did you get there? Which algorithm buries you deeply in recursion without being able to get out of it?

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

If you're desperate, exception is the way to go, but it's (rightfully so IMO) frowned upon.

+2


a source


Make your function optimized. Then there are no "functions above" to worry about.

+2


a source


No, you cannot reverse your recursion and go straight back to your main (). If your recursive function does not do different work after the recursive call, you would effectively do the same thing. I recommend restructuring a recursive function. A description of why you want to break out of recursion early on will also be helpful.

+1


a source


I got the same problem in nqueens backtracking algo.

The easiest way is to add a global boolean variable and use it to prevent any further action in your parent functions.

0


a source







All Articles