2
votes

Say we have the program:

int main(int argc, char** argv){
  if(argc < 3){
    printf("usage details\n");
    return EXIT_FAILURE;
  }
  dostuff();
  return EXIT_SUCCESS;
}

I've seen this as well:

int main(int argc, char** argv){
  if(argc < 3){
    printf("usage details\n");
    exit(EXIT_FAILURE);
  }
  dostuff();
  exit(EXIT_SUCCESS);
}

According to ISO/IEC 9899:1989 (C90):

The standard defines 3 values for returning that are strictly conforming (that is, does >not rely on implementation defined behaviour): 0 and EXIT_SUCCESS for a successful >termination, and EXIT_FAILURE for an unsuccessful termination. Any other values are >non-standard and implementation defined. main must have an explicit return statement at >the end to avoid undefined behaviour.

Also, according to ISO/IEC 9899:2011:

5.1.2.2.3 Program termination

If the return type of the main function is a type compatible with int, a return from the >initial call to the main function is equivalent to calling the exit function with the >value returned by the main function as its argument;11) reaching the } that terminates >the main function returns a value of 0. If the return type is not compatible with int, >the termination status returned to the host environment is unspecified.

It states that the return from main is equivalent to calling exit with the same return value.

That being said, the question is: Does it matter, whether you return from main and have it call exit for you, or exit from main

1
It's equivalent. As the standard says. i.e. interchangeable. - Mat
Depends. Are you ever planning to call main() yourself in your own code (perhaps recursively)? If so, exit() is a limiting choice. - John Deters
@JohnDeters: The standard also prohibits calling main(). - user149341
@duskwuff, that's the C++ standard. AFAIK, it's legal in C. That still doesn't make it a particularly good idea, tho. - John Deters
Yes, calling main is legal in C, but doesn't seems a good idea (especially if we define at_exit) - David Ranieri

1 Answers

2
votes

As methods of terminating a program, return and exit are closely related. In fact, the statement

return EXIT_SUCCESS;

in main is equivalent to

exit (EXIT_SUCCESS);  

The difference between return and exit is that exit causes program termination regardless of which function calls it. The return statement causes program termination only when it appears in the main function.