I was wondering when should I use exit() function over return statement. I can end the program with either of the following statements:
exit(0);
or
return;
Which one should I use and when?
Is there any advantage of using exit()?
I was wondering when should I use exit() function over return statement. I can end the program with either of the following statements:
exit(0);
or
return;
Which one should I use and when?
Is there any advantage of using exit()?
These two are very different in nature.
exit() is used when you want to terminate program immediately. If a call to exit() is encountered from any part of the application, the application finishes execution. return is used to return the program execution control to the caller function. In case of main() only, return finishes the execution.EDIT:
To clarify about the case when used in main(), quoting directly from the C11 standard, chapter §5.1.2.2.3, Program termination,
If the
returntype of themain()function is a type compatible withint, areturnfrom the initial call to themain()function is equivalent to calling theexit()function with the value returned by themain()function as its argument;11) reaching the}that terminates themain()function returns a value of0. If the return type is not compatible withint, the termination status returned to the host environment is unspecified.
So, basically, either
return 0;exit(0);will behave as same in the context of main().