Search code examples
creturn-valueexit-code

Is returning zero from main necessary, and how can the return value from main be useful?


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:

  1. Is returning zero always necessary from a C program?
  2. How is the return value from main() useful?

Solution

  • 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.