Explain the difference between return and exit in C

  • 2020-05-30 20:55:01
  • OfStack

Explain the difference between return and exit in C

1. exit is used to terminate the program at any time while the program is running. The parameter of exit is returned to OS. The main function is also implicitly called when it ends. The exit function runtime first performs the functions registered by the atexit() function, then does some cleaning of its own, refreshing all output streams, closing all open streams, and closing temporary files created through the standard I/O function tmpfile(). exit is to terminate a process, which will delete the memory space used by the process and return the error message to the parent process, while return is to return the value of the function and exit the function

2, return is language-level, which represents the return of the call stack; While exit is system call level, it represents the end of a process.

3. The exit function is to exit the application and return a state of the application to OS, which identifies some running information of the application.

4, and the machine and the operating system 1 is generally 0 for normal exit not 0 for abnormal exit

5, void exit(int status);

6, the parameter of atexit() function is a function pointer, and the function pointer points to a function with no parameters and no return value. The function prototype of atexit() is: int atexit (void (*)(void)); You can register up to 32 handlers in a single program using atexit(), which is called in the opposite order to the first one

Call, the last to register the first call.

If you want to do something at the end of the program, you can try using this function.


example:


#include... 

#include...

 
void f1(void)
{
  printf("exit f1\n");
}

void f2(void)
{
  printf("exit f2\n");
}

int main()
{
  atexit(f1);
  atexit(f2);


  printf("exit main\n");


  return 0;
}



If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!


Related articles: