Difference between return 1, return 0, return -1 and exit?

user3138495 picture user3138495 · Mar 24, 2014 · Viewed 192.7k times · Source

For example consider following code:

int main(int argc,char *argv[])
{
   int *p,*q;
   p = (int *)malloc(sizeof(int)*10);
   q = (int *)malloc(sizeof(int)*10);
   if (p == 0)
{
    printf("ERROR: Out of memory\n");
        return 1;
}


   if (q == 0)
{
    printf("ERROR: Out of memory\n");
        exit(0);
}

   return 0;
}

What does return 0, return 1, exit(0) do in the above program? exit(0) will exit total program and control comes out of loop but what happens in case of return 0, return 1, return -1.

Answer

Paolo picture Paolo · Mar 24, 2014

return from main() is equivalent to exit

the program terminates immediately execution with exit status set as the value passed to return or exit

return in an inner function (not main) will terminate immediately the execution of the specific function returning the given result to the calling function.

exit from anywhere on your code will terminate program execution immediately.


status 0 means the program succeeded.

status different from 0 means the program exited due to error or anomaly.

If you exit with a status different from 0 you're supposed to print an error message to stderr so instead of using printf better something like

if(errorOccurred) {
    fprintf(stderr, "meaningful message here\n");
    return -1;
}

note that (depending on the OS you're on) there are some conventions about return codes.

Google for "exit status codes" or similar and you'll find plenty of information on SO and elsewhere.


Worth mentioning that the OS itself may terminate your program with specific exit status codes if you attempt to do some invalid operations like reading memory you have no access to.