neuromancer
neuromancer

Reputation: 55489

Getting out of a recursive function at the topmost level in C++

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?

Upvotes: 2

Views: 3166

Answers (7)

Leero
Leero

Reputation: 57

I got the same problem in nqueens backtracking algo.

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

Upvotes: 0

mcdon
mcdon

Reputation: 5049

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.

Upvotes: 1

aspo
aspo

Reputation: 146

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

Upvotes: 2

sbi
sbi

Reputation: 224059

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.

Upvotes: 3

Paul R
Paul R

Reputation: 212949

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.

Upvotes: 4

sharptooth
sharptooth

Reputation: 170499

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.

Upvotes: 9

graham.reeds
graham.reeds

Reputation: 16476

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.

Upvotes: 2

Related Questions