I know it's been the convention in C89 to always return a 0 integer value from main in a C program, like this:
int main() {
/* do something useful here */
return 0;
}
This is to return a "successful" result to the operating system. I still consider myself a novice (or an intermediate programmer at best) in C, but to date I've never fully understood why this is important.
My guess is, this is a useful return result if you're tying the output of this program into the input of another, but I'm not sure. I've never found it useful, or maybe I just don't understand what the intention is.
My questions:
main()
useful?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.
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. return 0 means that the user-defined function is returning false. return 1 means that the user-defined function is returning true.
The return value for main is used to indicate how the program exited. If the program execution was normal, a 0 return value is used. Abnormal termination(errors, invalid inputs, segmentation faults, etc.) is usually terminated by a non-zero return.
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.
When writing scripts (like in Bash, or CMD.exe on Windows) you can chain some commands with the && and || operators.
Canonically, a && b
will run b
if the result of a
is zero, and a || b
will run b
if a
returned nonzero.
This is useful if you wish to conditionally run a command if the previous one succeeded. For example, you would like to delete a file if it contains word foo. Then you will use :
grep foo myfile && rm myfile
grep
returns 0 when there was a match, else nonzero.
Returning 0 is a convention. When a program returns 0, it can be assumed that it worked OK, without actually looking at what the program did (ahem :D).
As a widely used convention, that assumption is in a lot of places. As Benoit points out that's the case of the shell (UNIX and Windows) and other parts of the Operating system.
So answering your questions:
There's a related question with C++ and C great responses
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