Reputation: 1277
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; 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
Upvotes: 3
Views: 367
Reputation: 106102
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.
Upvotes: 3