Return from void functions in C++

C++Server Side ProgrammingProgramming

The void functions are called void because they do not return anything. “A void function cannot return anything” this statement is not always true. From a void function, we cannot return any values, but we can return something other than values. Some of them are like below.

A void function can return

A void function cannot return any values. But we can use the return statement. It indicates that the function is terminated. It increases the readability of code.

Example Code

 Live Demo

#include <iostream>
using namespace std;

void my_func() {
   cout << "From my_function" << endl;
   return;
}

int main() {
   my_func();
   return 0;
}

Output

From my_function

A void function can return another void function

In this approach, one void function can call another void function while it is terminating. The code will look like this.

Example Code

 Live Demo

#include <iostream>
using namespace std;

void another_func() {
   cout << "From another_function" << endl;
   return;
}

void my_func() {
   cout << "From my_function" << endl;
   return another_func();
}

int main() {
   my_func();
   return 0;
}

Output

From my_function
From another_function
raja
Published on 02-Apr-2019 17:17:59
Advertisements