return statement vs exit() in main() return statement vs exit() in main() c c

return statement vs exit() in main()


Actually, there is a difference, but it's subtle. It has more implications for C++, but the differences are important.

When I call return in main(), destructors will be called for my locally scoped objects. If I call exit(), no destructor will be called for my locally scoped objects! Re-read that. exit() does not return. That means that once I call it, there are "no backsies." Any objects that you've created in that function will not be destroyed. Often this has no implications, but sometimes it does, like closing files (surely you want all your data flushed to disk?).

Note that static objects will be cleaned up even if you call exit(). Finally note, that if you use abort(), no objects will be destroyed. That is, no global objects, no static objects and no local objects will have their destructors called.

Proceed with caution when favoring exit over return.

http://groups.google.com/group/gnu.gcc.help/msg/8348c50030cfd15a


Another difference:exit is a Standard Libraryfunction so you need to includeheaders and link with the standardlibrary. To illustrate (in C++),this is a valid program:

int main() { return 0; }

but to use exit you'll need an include:

#include <stdlib.h>int main() { exit(EXIT_SUCCESS); }

Plus this adds an additional assumption: that calling exit from main has the same side effects as returning zero. As others have pointed out, this depends on what kind of executable you're building (i.e., who's calling main). Are you coding an app that uses the C-runtime? A Maya plugin? A Windows service? A driver? Each case will require research to see if exit is equivalent to return. IMHO using exit when you really mean return just makes the code more confusing. OTOH, if you really do mean exit, then by all means use it.


There is at least one reason to prefer exit: If any of your atexit handlers refer to automatic-storage-duration data in main, or if you used setvbuf or setbuf to assign to one of the standard streams an automatic-storage-duration buffer in main, then returning from main produces undefined behavior, but calling exit is valid.

Another potential usage (usually reserved for toy programs, however) is to exit from a program with recursive invocations of main.