jwaixs said:
Hello,
I was wondering, what's the difference between exit and return in the
main() function? For me they both look the same, or aren't they? And if
they aren't, which should I use in which situation?
They are almost equivalent. As far as I know there
are only two differences:
- The main() function can be called recursively, like
any other C function. If it is, only the return from
the first call terminates the program; they program
just keeps on running when a subsequent call returns.
Of course, exit() will terminate the program regardless.
Here's a silly program that prints its command-line
arguments in reverse order:
#include <stdio.h>
int main(int argc, char **argv) {
if (argc > 0) {
main(argc - 1, argv + 1);
puts (*argv);
}
return 0;
}
Clearly, this program's behavior would be completely
different if exit() were used instead of return.
- When main() returns, all its local variables cease to
exist. If program wrap-up activities try to refer to
these variables (via pointers stored earlier), there
will probably be trouble. Functions registered with
atexit() are a potential source of trouble here; so are
setbuf() and setvbuf() if they use `auto' buffers and
their streams have not yet been closed. Calling exit(),
though, leaves the caller's variables intact.
Personally, I prefer to return from main rather than call
exit(), but it's a weak preference.
Also I was wondering if it whould be wise to combine the standard
status with return.
exp:
int main(){
printf("Hello World\n");
return EXIT_SUCCESS;
}
You should always return some kind of value from main() or
pass some kind of value to exit(). The three "portable" values
are 0, EXIT_SUCCESS, and EXIT_FAILURE; your system may possibly
recognize other values as well.