Open In App
Related Articles

Return From Void Functions in C++

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Void functions are known as Non-Value Returning functions. They are “void” due to the fact that they are not supposed to return values. True, but not completely. We cannot return values but there is something we can surely return from void functions. Void functions do not have a return type, but they can do return values. Some of the cases are listed below:
 
1) A Void Function Can Return: We can simply write a return statement in a void fun(). In fact, it is considered a good practice (for readability of code) to write a return; statement to indicate the end of the function. 

CPP

// CPP Program to demonstrate void functions
#include <iostream>
using namespace std;
 
void fun()
{
    cout << "Hello";
 
    // We can write return in void
    return;
}
 
// Driver Code
int main()
{
    fun();
    return 0;
}

                    

Output
Hello

Time Complexity: O(1)

Space Complexity: O(1)

2) A void fun() can return another void function: A void function can also call another void function while it is terminating. For example, 

CPP

// C++ code to demonstrate void()
// returning void()
#include <iostream>
using namespace std;
 
// A sample void function
void work()
{
    cout << "The void function has returned "
            " a void() !!! \n";
}
 
// Driver void() returning void work()
void test()
{
    // Returning void function
    return work();
}
 
// Driver Code
int main()
{
    // Calling void function
    test();
    return 0;
}

                    

Output
The void function has returned  a void() !!! 

Time Complexity: O(1)

Space Complexity: O(1)

The above code explains how void() can actually be useful to return void functions without giving errors.
 
3) A void() can return a void value: A void() cannot return a value that can be used. But it can return a value that is void without giving an error. For example,

CPP

// C++ code to demonstrate void()
// returning a void value
#include <iostream>
using namespace std;
 
// Driver void() returning a void value
void test()
{
    cout << "Hello";
 
    // Returning a void value
    return (void)"Doesn't Print";
}
 
// Driver Code
int main()
{
    test();
    return 0;
}

                    

Output
Hello

Time Complexity: O(1)

Space Complexity: O(1)



Last Updated : 27 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads