• Register
search
Log In

The return statement is one of several means we’ll use to exit a function. When the return statement is used at the end of main, as return 0, the value 0 indicates that the program has terminated successfully. The right brace, }, indicates the end of the function main. According to the C++ standard, if program execution reaches the end of main without encountering a return statement, it’s assumed that the program terminated successfully-exactly as when the last statement in main is a return statement with the value 0. For that reason, we omit the return statement at the end of main in subsequent programs. The return statement may or may not return anything for a void function, but for a non-void function, a return value must be returned.

 

Ways to use return statements

For not returning a value:

In C++ you can skip the return statement only for void types.

 

  • Not using a return statement in void return type function: when we have a function which is not returning anything, the void type is used. So if there is a void return type function then no return statement will be used inside the function. The syntax for doing this is 

    void func()
    {
        .
        .
        .
    }

     

  • Using a return statement in void return type function: Can we use the return statement in void return type function?  Yes, we can use the return statement inside a void return type function. If a function has a return statement inside it, then we can also use the syntax without any problem.

    void func()
    {
        return;
    }

     

 

For returning a value:

For returning a value, the return statement must be followed by the return value. The syntax for returning the statement is

return-type func()
{
    return value;
}

 

Wrong syntax of using return statements

If we try to return a value in a void return type by a return statement, the compiler will show errors. For example

void func()
{
    return value;
}
#include <iostream> 
using namespace std; 
  
// void method 
void Print() 
{ 
    printf("Welcome to C++"); 
  
    // void method using the return 
    // statement to return a value 
    return 10; 
} 
  
// Driver method 
int main() 
{ 
  
    // Calling print 
    Print(); 
  
    return 0; 
} 

 

posted Jun 3 in c++ 100 points

2 Comments

Nice article very impressive

Thanks man for appreciating. Loved you appreciationheart