C++ – return statement vs exit() in main()


Should I use exit() or just return statements in main()? Personally I favor the return statements because I feel it's like reading any other function and the flow control when I'm reading the code is smooth (in my opinion). And even if I want to refactor the main() function, having return seems like a better choice than exit().

Does exit() do anything special that return doesn't?

Best Answer

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.