Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
Yes, I think this should serve the purpose, though throwing an exception is not a nice way on a success, I mean the caller would not expect to look for an result in catch block...
is there any better way
setjmp in the first call to the recursive function and then longjump to the status saved in setjmp when you want to return
recurse(&success_flag, args....)
{
if(!(*success_flag))
recurse(sucess_flag, args...);
if(success)
foo();
}
foo()
{
*success_flag = 1;
exit();
}
You can use tail recursion. Last line of the function will be a recursion call. so if you return then all the functions below the stack will just return.
def abc():
if cond:
do something
else:
return
abc()
if (resultFound) { return; }
Does that help you at all? I'm really not quite sure what you're asking.
@eugene : if (resultFound) { return; }
it would only return from that perticular call of the function.
i meant with the question: when the objective of the recurssion is met, it should not execute remaining calls in the recurssion stack...
This should do I guess!
recurse(&success_flag, args....)
{
if(!(*success_flag))
recurse(sucess_flag, args...);
if(success)
*success_flag = 1;
}
you havent understood the question yet..
after success_flag is set to 1, further recursive call cannot be made.. but already called recursive functions will continue to execute
Using Setjump LongJump in C? or Throw an Exception in C++? Though Stack unwinding will happen prorperly while throwing Exception in C++.
- nerd July 22, 2012I think this is what he wanted to ask.