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!