This is likely a stupid question but I always find myself wondering which is the standard.
In most (not to say all) C++ first examples you may see the main function returning 0 value. This means the operation went ok or not?
Which is the standard way of doing it?
By the way, is it better to return an integer or a boolean in this case?
Thank you guys!
return 0: A return 0 means that the program will execute successfully and did what it was intended to do. return 1: A return 1 means that there is some error while executing the program, and it is not performing what it was intended to do.
The main function is generally supposed to return a value and after it returns something it finishes execution. The return 0 means success and returning a non-zero number means failure. Thus we "return 0" at the end of main function. But you can run the main function without the return 0.It works the same .
Short Answer: Nothing. Better Answer: return 0 it's used in main like a signal for know the exit of program was a success when return 0 executes. Best Answer: Still nothing because compilers already "put" return 0 in the the end of your code if you not explicit.
in main function return 0 or exit(0) are same but if you write exit(0) in different function then you program will exit from that position. returning different values like return 1 or return -1 means that program is returning error .
0
or EXIT_SUCCESS
means success. EXIT_FAILURE
means failure. Any other value is implementation defined, and is not guaranteed to be supported. In particular, std::exit(1)
or return 1;
are not actually guaranteed to indicate failure, although on most common systems they will.
EXIT_SUCCESS
and EXIT_FAILURE
are defined in <cstdlib>
.
Edit: I suppose it might be useful to give a system-specific example:
The GNU make utility returns an exit status to the operating system:
The ability to set multiple different values of failure means you can specify exactly how your program failed. There are two caveats, however:
0 is ok, other values are an error code. The main function should return an int and nothing else according to the standard. The question has been discussed before at What should main() return in C and C++?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With