Open In App

return 0 vs return 1 in C++

The Return statement in C/C++:

There are two scenarios in which return statements will be used:                  



Method 1. Inside the main function:

Important characteristics of the return statement: 



Below is a program to illustrate the use of return 0 and return 1 inside the main function:




// C++ program to divide two numbers
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    // Given integers
    int a = 5, b = 0;
 
    if (b == 0) {
 
        // The below line is used to print
        // the message in the error window
        // fprintf(stderr, "Division by zero"
        //                 " is not possible.");
 
        // Print the error message
        // as return is -1
        printf("Division by zero is"
               " not possible.");
        return -1;
    }
 
    // Else print the division of
    // two numbers
    cout << a / b << endl;
 
    return 0;
}

Output:
Division by zero is not possible.

Time Complexity: O(1)
Auxiliary Space: O(1)

Method 2. Inside the user-defined function:

Below is a program to illustrate the use of return 0 and return 1 inside the user-defined function:




// C++ program to demonstrate the use
// of return 0 and return 1 inside
// user-defined function
#include <iostream>
using namespace std;
 
// Utility function returning 1 or
// 0 based on given age
int checkAdultUtil(int age)
{
    if (age >= 18)
        return 1;
    else
        return 0;
}
 
// Function to check for age
void checkAdult(int age)
{
    // Checking on the basis
    // of given age
    if (checkAdultUtil(age))
        cout << "You are an adult\n";
    else
        cout << "You are not an adult\n";
}
 
// Driver Code
int main()
{
    // Given age
    int age = 25;
 
    // Function Call
    checkAdult(age);
 
    return 0;
}

Output:
You are an adult

Time Complexity: O(1)
Auxiliary Space: O(1)

Conclusion:

Use-case return 0 return 1
In the main function return 0 in the main function means that the program executed successfully. return 1 in the main function means that the program does not execute successfully and there is some error.
In user-defined function return 0 means that the user-defined function is returning false. return 1 means that the user-defined function is returning true.

Article Tags :