There is an important semantic difference in C ++. The return
will close the scope and call all pending destructors. If the application is closed, rarely will the call of the destructors produce a different result, but technically it is possible for one of them to do something that is important to the end of the application, or to print relevant information for the user. >
Even though the action looks the same, the exit()
function causes a premature exiting of the application. Then execution is terminated almost immediately. exit()
finalizes static objects, but not destructors. The abort()
and _Exit()
neither does this and it closes on time.
There's a difference even in C if you have functions registered with atexit()
. These functions will always run no matter how the application is shutting down. But there will be undefined behavior if one of the linked functions in atexit()
has reference to some data in stack . Something like setbuf()
and setvbuf()
. This is especially important in C. documentation
Note that the main()
function is not special and can be called within the application. In this case there will be an important difference since a return
will not terminate the application, although in the context of the question this would not happen. But understand that if what you wrote will not be called in the operating system and this main()
is part of a module that will be loaded and used in another application, your module will terminate the application and not only your code if you use exit()
, return
will then be the most appropriate in most situations.
A call to main()
can be recursive, although it should not. Of course there is difference in this case, but it falls into what I said in the previous paragraph.
That's why you always have to choose the most semantically correct way . If you want to terminate the application immediately use exit()
, otherwise use return
. Many people say that if main()
is terminating the application, exit()
is the most appropriate. Not everyone agrees, especially in C ++. That's why it's good to understand the workings, the implications of each and do not blindly follow rules.
I do not know if it counts as a difference, because it is a function, to use it, you need to use a #include
so that it is available, and if the code unit it contains would not enter the application, the executable will be a bit bigger. The command is always available.