Why return 0; and not return x;?

Hello everyone,

I started learning C++ today and I want to get a good grasp of it asap *lol*.
Well I have no prior knowledge of programming languages at all so this is my first and I chose C++ because of its complexity and from what I read it will be easier to learn other languages once I'm "good" with C++.

So, I have downloaded the tutorial from here and bought the C++ Primer 5Ed(mostly suggested here as I read) which are both really useful for a start.

My first program is the typical "Hello World!" which was easy to make but I'm confused with the return statement (as in the topic question).

From what I understood, the return statement will simply terminate the function but why use return 0; and not return x; (where x is a positive or negative integer) when both work (I tried to change it)??

Below is an example of what I tried:

#include <iostream>
using namespace std;
int main()
     cout << "Hello World!";
     return -60; // This works just as fine as it would with return 0

Result was Hello World! followed by "Process returned -60 (long HEX code) execution time: z (where z is the time in s)

Please help me out with that. It's a simple problem but it bugs me out lol. I have other questions posted :D

The return value from main is something that can be read by the operating system that ran the program. It's a way that your program can report something back to the OS that called it.

It can mean anything you want it to, but usually, it's used to indicate whether the program ran successfully or whether there was an error. The convention is that returning "0" indicates that it ran successfully, and returning another number indicates some kind of error or other unusual state.

When someone just ends their main function with "return 0", with no other conditional return statements to return other values, it usually just means that they're not bothering to use the return value for anything.

If it's useful to have your program return -60 instead of 0, then by all means do it. Just make sure that in your documentation, you explain that return value, so that other users know how to interpret it.
Last edited on
Topic archived. No new replies allowed.