Why do we use return; statement in a void function?

sha*_*adw 3 c

return; in a void function. What does it actually do?

void function() {
    if(x==NULL) {
        return;
    }
    else{
        /////
    }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*mit 7

In the example you've shown, the return does nothing. But think about this example:

void do_the_thing()
{
    if(it's already done)
        return;

    do the thing;
}
Run Code Online (Sandbox Code Playgroud)

If doing the thing is expensive, or causes problems if it's been done already, you'd like logic like this. And, besides "expense", there are plenty of reasons a function might choose to do less than its full repertoire of actions during any given call.

In other words, returning from a void function, although it won't return a value, will at least keep the function from doing any of its later stuff.

(Now, with that said, having a return in the middle of the function isn't the only way of achieving such a thing. Instead of if statements that cause the function to return early, you could use if statements or else clauses to cause the function to only do things if it needs to. Returning to my example, you could also write

void do_the_thing()
{
    if( ! already done) {
       do the thing;
    }
}
Run Code Online (Sandbox Code Playgroud)

And this leads to an eternal style debate, namely, whether it's a good or bad idea to have multiple return statements sprinkled through a function, or if there should always be exactly one, at the end.)