'how does return statement work in a void function?
This function works fine in a program. But can I get the explanation of the work of return statement in preorder function... if statement?
struct myNode{
int data;
myNode *prev, *next;
};
void preOrder(myNode *node) {
if (node == NULL)
return;
cout << node->data << " ";
preOrder(node->prev);
preOrder(node->next);
}
Solution 1:[1]
return means the execution of the function will stop at this line and below lines of code will not be executed. Since below we have node->data and we don't want to access data of node if node is null so we wrote return command there.
Solution 2:[2]
If the function returns void, return still governs control flow.
In this case, if node is NULL, the function exits immediately, and subsequent code in the function is not executed. By doing so, this particular function ensures that the data member cannot be accessed on a null pointer. This is a common pattern you will see in many functions.
Nitpick: as this is C++ rather than C, nullptr would be more idiomatic than NULL.
Solution 3:[3]
Void is a valid return result just like anything else. The only difference is there is no object being returned (simply return nothing).
In general whatever the return type of a function, the return statement causes the function to exit, which will cause the return value to be copied (or moved) to the destination location of the call and all local objects (currently initialized) to be destructed. The only difference between void and any other type that copying or moving a non object is very cheap.
void myFunc1()
{
if (condition) {
return; // return nothing (same as void).
}
// Do Stuff;
// Don't need an explicit return for void.
// But you can have one if you want.
return;
}
You can also return the result of a void call from another void function.
void myFunc2()
{
return myFunc1(); // If myFunc1 returns a void.
// and this function returns a void.
// you have a valid return.
}
I know it does not seem useful. But when you start playing with templates and the return type is not always obvious, it is useful to know that void behaves exactly like other types being returned from a function (except there is no void object itself so is very cheap to construct :-) ).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chris |
| Solution 2 | |
| Solution 3 | Martin York |
