I have a question on return and recursive functions.
This is again based off of a binary Tree which I am currently working on. The code is
void Tree::display()
{
if( !root_ )
return;
display_r(root_);
}
void Tree::display_r(Tree *node)
{
if( 0 == node )
return;
display_r(node->left_);
std::cout << node->value_ << std::endl;
display_r(node->right_);
}
This is working code. Compiles and runs without fail, printing the numbers from smallest to largest. However, this did not used to be so.
The code above was first written with
return display_r(node->left_);
std::cout << node->value_ << std::endl;
return display_r(node->right_);
which did not work. It simply returned without printing anything. Which makes sense, the return doesn’t allow the code to move downwards.
This brought me to an interesting question. While writing the tree I was often wondering whether or not it was a good place to use return in a recursive function or not. Obviously, anytime the return is the last command executed in the block of code is okay to use. I think it’s even okay to use in the display() function as
void Tree::display()
{
if( !root_ )
return;
return display_r(root_);
}
So my question is: when do I know for sure I can use return, and when shouldn’t I use it? Are there gray areas where it’s up to me to decide what’s best, and is there a safety-net? As in, “When in doubt, don’t use returns in a recursive function?”
Thanks!
I suggest studying the return keyword more carefully and also practicing recursion a bit more.
Here the return is necessary:
… as this is the base case (aka general solution) for your recursive algorithm. When you encounter a null for a child, you stop, otherwise continue. Note that this code is part of an if statement. It is only executed in certain circumstances (precisely the circumstance for which you want to prematurely return out of the function and stop recursing).
In your particular case you could also write this without using return at all, and very easily:
As an aside, and without meaning to offend, it looks as though you are borrowing from examples without quite understanding how they work. Try to think for yourself and play with the code and try to understand it. If need be, put a comment next to every instruction indicating what it does in a way that’s understandable to you.
Also do try to learn the debugger; I can’t emphasize this enough. A lot of university students go through their whole undergraduate degree without being taught how to use a debugger, and that’s a real shame. It should be one of the first things taught! Tracing through your code with a debugger will really help you to see the behavior of the code that you write. If you aren’t being taught how to use it, I recommend learning how to use it for yourself. It will show you how the machine goes through every line of code you write, step-by-step.