+ 1
Why a function main() has to return value!!!!!! Don't understand about return 0
Help!! plz!!!
5 Answers
+ 1
See Omar's answer. It is a way for your program to return something that tells you (or, to be more accurate, tells the parent process) if there were any issues during execution.
For more details, see:
https://en.m.wikipedia.org/wiki/Exit_status
A few more notes:
1) this is NOT Linux-specific. See %errorlevel% i. Windows, for example
2) this has nothing to do with the program being compiled or interpreted. An interpreted program (or even a shell script) can just as well return an exit code
3) this is unrelated to exceptions and exception handling. Compiled programs can raise exceptions just fine :)
+ 6
It's just a check up if everything went right in your code. It's a compiled language - you don't go through the written code and interpret it (which would allow to raise an exception if an error encountered). You run it "all at once" and if everything is okay, the code returns 0. If wrong, a returned number can be interpreted and understood what kind of a runtime error was encountered.
+ 3
In some OS like linux if main() of a program didnt return 0 and returned another value it mean that there is an error
+ 2
Still not clear
+ 2
You can use the return value outside the program, like a batch:
//Program.exe
#include <iostream>
int main()
{
std::cout << "Enter a value to return:\n";
int a;
std::cin >> a;
return a;
}
//c.bat
@echo off
program.exe
if %errorlevel%==0 ECHO Success
if %errorlevel% gtr 0 ECHO Failure
If you start the batch, the program will be called, if the user enters 0 then the program will return 0.
Windows stores the last return value to %errorlevel% and you can then do whatever you want with that, in this case it will display "Success" to the screen and "Failure" with a number bigger than 0.