return value for void

The function below has a return type of void. But to end the recursion in it, we call
 
return;  

when the condition
 
if(n == nullptr)

is met.

What action is performed by the return statement in this case?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void BSTree::preOrder(Node* n)
{
    if(n == nullptr)
    {
        return;
    }
    else
    {
       cout << n->getData() << " ";
       preOrder(n->getleft());
       preOrder(n->getright());

    }
}
What action is performed by the return statement in this case?


This function stops running, and the program continues running from whatever called this function.
The function can be easily be written without using return.

1
2
3
4
5
6
7
8
9
void BSTree::preOrder(Node* n)
{
    if(n != nullptr)
    {
       cout << n->getData() << " ";
       preOrder(n->getleft());
       preOrder(n->getright());
    }
}
I believe return; can't be used in void. It's a type of function that never returns anything.
return; can be used in a function that doesn't return any variable (such as this function above).

A void function doesn't return any value, but it still returns. If you couldn't use return; in the function, how would you make it stop where you wanted?
Last edited on
Topic archived. No new replies allowed.