Thread: Return 0; or Return 1;

  1. #1
    Registered User Triggercut's Avatar
    Join Date
    Apr 2016
    Posts
    4

    Return 0; or Return 1;

    I am still not sure what this line means. For example in the hello world program...

    Code:
    1 2 3 4 5 6 7 8 9 10 11
    #include <iostream> using namespace std; int main() { cout<<"HEY, you, I'm alive! Oh, and Hello World!\n"; cin.get(); return 1; }

    The return 1; is used here, Why? And sometimes I see return 0; used in this hello world program as well. What is the difference between the two? and What is its purpose/point? Is it just merely some kind of line of code to tell your computer and yourself the program executed correctly?

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    Well, it should be 0. I mean the standard defines that main() returns 0 implicitly.

    Compile this though, what does it say?
    Code:
    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    
    int main ()
    {
       cout << "The conventional return value for success on this platform=" << EXIT_SUCCESS << endl;
       cout << "The conventional return value for failure on this platform=" << EXIT_FAILURE << endl;
    }
    It is possible that other examples just go against convention for no reason.
    Last edited by whiteflags; 04-11-2016 at 07:03 PM.

  3. #3
    Registered User Triggercut's Avatar
    Join Date
    Apr 2016
    Posts
    4
    Thanks for the reply whiteflags! That hello world program I pulled out of the tutorial on this website, I still don't understand what you mean. 0 or 1? What is the point of this line of code? What is the purpose? Is it supposed to be a piece of code there because of the int main()? The explanation of return 1; on this website is just too much jargon for me to understand. I am just beginning code. Could you give me the 'kiddy' explanation of this last line of code in the hello world program?

    "Upon reaching the end of main, the closing brace, our program will return the value of 0 (and integer, hence why we told main to return an int) to the operating system. This return value is important as it can be used to tell the OS whether our program succeeded or not. A return value of 0 means success and is returned automatically (but only for main, other functions require you to manually return a value), but if we wanted to return something else, such as 1, we would have to do it with a return statement:"

  4. #4
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Try this program to return various values from main:
    Code:
    #include <iostream>
    #include <cstdlib>  // defines EXIT_FAILURE and EXIT_SUCCESS
    
    int main() {
        std::cout << "EXIT_SUCCESS: " << EXIT_SUCCESS << '\n';
        std::cout << "EXIT_FAILURE: " << EXIT_FAILURE << '\n';
    
        std::cout << "Return: ";
        int ret;
        std::cin >> ret;
    
        return ret;
    }
    Returning 0 (or equivalently EXIT_SUCCESS, which is always 0) from main or calling exit() with 0 or EXIT_SUCCESS indicates to the OS that the program executed successfully. Interestingly, returning 0 doesn't necessarily return the value 0 to the OS but instead will return whatever value the system requires to indicate success, i.e., if the OS requires the value 42 then returning 0 will be translated into returning 42.

    Returning a non-zero value generally indicates failure, with different values possibly indicating different failure modes, depending on the system. For maximum portability you should return EXIT_FAILURE, a macro with a non-zero value but not necessarily 1.

    Also, C++ (and C99 or higher) will automatically return 0 at the end of main if you leave out the return statement.

    If you're on linux, try running your program like this:

    $ ./yourprog && echo "success" || echo "failure"

    The shell should echo "success" if you return 0 and "failure" if you return a non-zero value. You could also try the following to echo the return status. On linux this value will be between 0 and 255, inclusive, even if you return an int outside that range:

    $ ./yourprog ; echo $?

    Note that the macros EXIT_SUCCESS (or simply 0) and EXIT_FAILURE (not 0 but not necessarily 1 either) are for portability. Any particular system could have far more options than that, but using them is not portable.

  5. #5
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Some unix tools will return 1 or 2 depending on the error type, and 0 otherwise. Some tools like GNU make rely on the fact that a non-zero return indicates an error.

    The use of this value to indicate error is convention only. You could use it for something else if your program is run as part of a script.

    For reference, Windows allows you to return any integer value.

    EDIT:
    Also, calling std::abort will cause your program to return EXIT_FAILURE. Calling std::terminate will by default call std::abort, which happens automatically in certain unrecoverable situations.
    Last edited by King Mir; 04-11-2016 at 11:04 PM.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  6. #6
    Registered User
    Join Date
    May 2010
    Posts
    4,633
    For reference, Windows allows you to return any integer value.
    But remember the only portable values are EXIT_SUCCESS, EXIT_FAILURE, and zero.

    Also gcc has much lower limits, than Windows, on the allowable exit() value (From this link:):
    Warning: Don’t try to use the number of errors as the exit status. This is actually not very useful; a parent process would generally not care how many errors occurred. Worse than that, it does not work, because the status value is truncated to eight bits. Thus, if the program tried to report 256 errors, the parent would receive a report of 0 errors—that is, success.

    For the same reason, it does not work to use the value of errno as the exit status—these can exceed 255.

    Jim

  7. #7
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    The inquisitor clearly doesn't understand what "returning" means, so you fellows' explanations are not really very helpful. Maybe step back and actually pay attention to the question.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  8. #8
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Quote Originally Posted by brewbuck View Post
    The inquisitor clearly doesn't understand what "returning" means, so you fellows' explanations are not really very helpful. Maybe step back and actually pay attention to the question.
    algorism addressed the OP's question directly in post #4. Perhaps you missed it?

  9. #9
    Registered User Triggercut's Avatar
    Join Date
    Apr 2016
    Posts
    4
    Well thanks for all your replies everyone, I'll just keep researching this. I may get it one day.

  10. #10
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Programs return 0 to the operating system to signal "no error". This is just a convention, but one that is used by the shell environment. For example, if your program is called foo, then you can type the following in the Windows shell:

    Code:
    foo.exe & echo Foo executed successfully.
    Then, you will see the message "Foo executed successfully" if and only if foo exits with return code 0 (i.e. it "succeeded").

  11. #11
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by Matticus View Post
    algorism addressed the OP's question directly in post #4. Perhaps you missed it?
    I read that reply. It's not answering the OP's question.

    It sounds to me like OP doesn't understand what it means for a function to "return." You guys are talking about the meaning of the possible return codes, but you haven't bothered explaining what returning from a function actually means.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  12. #12
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Quote Originally Posted by brewbuck View Post
    I read that reply. It's not answering the OP's question.

    It sounds to me like OP doesn't understand what it means for a function to "return." You guys are talking about the meaning of the possible return codes, but you haven't bothered explaining what returning from a function actually means.
    I'm assuming the responders in this thread were under the impression the OP was specifically asking about why a value is returned from the main function (which seems a fair interpretation, based on their wording), instead of the more general case of returning values from functions in general.

    However, I'm more curious as to why you chose to criticize the responses in this thread instead of offering an answer yourself based on your interpretation of the question.

  13. #13
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    I mean if returning itself is the problem in understanding, I think a function besides main() may help OP understand. It's really important to take a bird's eye view on this subject.

    In general all functions that use return values use them to communicate information. What information? It depends. A lot of the time, the only good answer is "read the friendly manual." Once that is understood for one particular function, that concept needs to be extended to other functions, which are using return values to similar ends.

    As a concrete example, I wrote a small program that solves the quadratic formula:
    Code:
    #include <iostream>     // for cin, cout
    #include <cerrno>       // for errno
    #include <cmath>        // for sqrt
    #include <algorithm>    // for swap (C++ 98)
    #include <utility>        // for pair or swap
    #include <limits>        // for NaN
    using namespace std;
    
    
    /* Returns the solutions for a polynomial of degree 2 using the quadratic formula.
       If the results are complex numbers, then the return value will be a pair of NaNs.
    */
    pair<double, double> poly2zero(double a, double b, double c)
    {
        errno = 0;
        double nan = numeric_limits<double>::quiet_NaN();
        pair<double, double> r = make_pair(nan, nan);
        
        double discriminant = sqrt(b * b - 4 * a * c);
        if (errno != EDOM)
        {
            double denom = 2 * a;
            r.first  = ((-b) - discriminant) / denom;
            r.second = ((-b) + discriminant) / denom;
            
            if (min(r.first, r.second) != r.first)
            {
                // swap so the first root is always the lesser of the two:
                swap(r.first, r.second);
            }
        }
        return r;
    }
    
    int main() 
    {
        double a, b, c;
        cout << "This program will solve polynomials of degree 2 ax^2 + bx + c.\n";
        cout << "Enter A: "; 
        cin >> a;
        cout << "Enter B: ";
        cin >> b;
        cout << "Enter C: ";
        cin >> c;
        
        pair<double, double> answer = poly2zero(a, b, c);
        cout << "Your solutions are " << answer.first << '\t';
        cout << answer.second << '\n';
    }
    So the return value of poly2zero(a,b,c) is not meaningless, agreed? It is actually the two roots of the equation ax2 + bx + c = 0 in .first and .second.

    One way you can use the program is to find the golden ratio:
    Code:
    This program will solve polynomials of degree 2 ax^2 + bx + c.
    Enter A: 1
    Enter B: -1 
    Enter C: -1
    Your solutions are -0.618034    1.61803
    Return values are one way to pass information along in a program. In more concrete terms, it works the same way you pass a baton in a race. The answer in this program is the baton, and the variables in the program hold the baton at different points during a run. Without them, it would actually be harder to write this, and use all sorts of other functions. main() is just one concrete example, for the use of the operating system, which communicates whether there was a problem or not.

    The example I posted could even be amended to communicate errors the way main() does, because it returns NaNs if there wasn't a real number solution. It's:
    Code:
    if (answer.first == answer.first) { // NaNs are never equal to each other.
        cout << "Your solutions are " << answer.first << '\t';
        cout << answer.second << '\n';
    } else {
       cout << "The polynomial does not have a real number solution (NaN).\n";
    }
    HTH.

  14. #14
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by Matticus View Post
    However, I'm more curious as to why you chose to criticize the responses in this thread instead of offering an answer yourself based on your interpretation of the question.
    I don't really have much time to write responses anymore, unfortunately. I didn't mean to make a stinging criticism, just pointing out that I thought OP's question was being misinterpreted. If it seemed rude that was not my intention.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  15. #15
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Quote Originally Posted by brewbuck View Post
    just pointing out that I thought OP's question was being misinterpreted.
    It doesn't seem to be a question about returning values from functions generally but about returning a value from main specifically. The OP even guesses the correct answer given that interpretation.

    Although perhaps it was a question about what it means to "return from main" which is different from returning from any other function. It's more akin (if not identical) to a child process exiting and "returning" an exit status to its parent then simply returning a value from a function.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Return pointer to a vector of objects as a function return
    By Adaptron in forum C++ Programming
    Replies: 14
    Last Post: 04-07-2016, 09:23 AM
  2. Replies: 1
    Last Post: 07-04-2007, 12:20 AM
  3. Replies: 12
    Last Post: 04-07-2007, 11:11 AM
  4. Replies: 6
    Last Post: 04-09-2006, 04:32 PM
  5. Replies: 4
    Last Post: 07-15-2005, 04:10 PM

Tags for this Thread