• Register
+1 vote
12 views

Problem:

I am exploring the c++ programming language nowadays. It’s really interesting to learn new things every day. I was trying to adopt the methods in c++ but struggling to return values from a void method. I actually want to know that if it is possible to return values from a void method or you may have a return statement in a void method.

Thanks for your co-operation in this learning process. I really appreciate your effort.

Thanks again.

ago by (6k points)  
reopened ago by

1 Answer

+1 vote
 
Best answer

Solution:

Void functions are “void” due to the fact that they are not supposed to return values. True, but not completely. We may not able to return value from a void function but we may return something others from a void function in various cases. Let’s see how to do it.

#include <iostream> 
using namespace std; 
  
void func() { 
   cout << "I am a void function";   
   return;  
} 
  
int main() { 
   func(); 
   return 0; 
}

We simply wrote a return statement inside the void function and call the void function from the main function. This program provides an output of:

I am a void function

We also can return a void function inside a void function. Let’s see:

#include<iostream> 
using namespace std;   
void func() { 
    cout << "The is a void function"; 
} 
  
void anotherFunc() { 
    return func(); 
} 
  
int main() { 
    anotherFunc; 
    return 0; 
} 

So, here we’ll get the out of the void func because of passing the function into another void function, and later on, call it from the main function.I hope these above examples make things clear to you.

Thanks

ago by (17.9k points)  
selected ago by
...