2

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()?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Sourav Kanta
  • 2,727
  • 1
  • 18
  • 29

1 Answers1

8

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 return type of the main() function is a type compatible with int, a return from the initial call to the main() function is equivalent to calling the exit() function with the value returned by the main() function as its argument;11) reaching the } that terminates the main() function returns a value of 0. If the return type is not compatible with int, 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().

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261