There is an important semantic difference in C++. The return
will close the scope and call all the pending destructors. If it is the same application shutdown, rarely will the destructors call produce a different result, but technically it is possible that some of them do something that is important for the purpose of the application, even if it is to print information relevant to the user or log.
Even if the action looks the same, the function exit()
causes a premature exit from the application. Then the execution is terminated almost immediately. The exit()
ends static objects, but not destructors. Already the abort()
and _Exit()
neither does it and closes on time.
There is difference even in C if you have registered functions with atexit()
. These functions will always be executed no matter how the application is being terminated. But there will be undefined behavior whether one of the atexit()
has reference to any data in stack. Something like setbuf()
and setvbuf()
. This is important especially in C.documentation
Note that the function main()
is not special and can be called within the application. In that case there will be an important difference since a return
will not terminate the application, even if in the context of the question this would not happen. But understand that if what you wrote is not called by the operating system (one way or another) 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 the exit()
, the return
then it will be the most suitable in most situations.
A call to main()
may be recursive, although it should not be. Of course there is a 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 close the application immediately use exit()
, otherwise use the return
. Many people say that if the main()
is closing the application, the exit()
is the most appropriate. Not everyone agrees, especially in C++. That is why it is good to understand the functioning, the implications of each and do not follow rules blindly.
I don’t know if it counts as a difference, because it’s a function, to use it you need to use a #include
for it to be available, and if the unit of code it contains would not enter the application, the executable will be a little larger. The command is always available.
It does not seem correct to say that the function "Exit" closes the application "immediately". This comment would apply better to the functions "_Exit" and "_Exit". See https://msdn.microsoft.com/en-us/library/6wdz5232.aspx, https://linux.die.net/man/3/exit and https://linux.die.net/man/2/_Exit.
– zentrunix
@Joséx. That’s a question, right? Questions assume that there is no full domain of information. The answer explains this more adequately. I can put on these other functions in the answer, think it helps?
– Maniero