Exit C ++ program with status

What function is used in C ++ stdlib to exit a program with a status code?

In Java there is:

System.exit(0) 
+6
source share
3 answers

Assuming you have only one thread:

 #include <iostream> int main() { std::cout << "Hello, World!\n"; return(0); // PROGRAM ENDS HERE. std::cout << "You should not see this.\n"; return(0); } 

Conclusion:

 Hello, World! 

return(0); can be placed anywhere - this will end with int main() and therefore your program.


Alternatively, you can call exit(EXIT_SUCCESS); or exit(EXIT_FAILURE); from any place you like:

 /* exit example */ #include <stdio.h> #include <stdlib.h> int main () { FILE * pFile; pFile = fopen("myfile.txt", "r"); if(pFile == NULL) { printf("Error opening file"); exit (1); } else { /* file operations here */ } return 0; } 
+10
source

In addition to other answers, you can also cause interruption, termination, quick_exit (exits without calling destructors, deactivation, etc., hence the name)

stop canceling calls by default, but can call any completion handler that you set.

An example of using abort and set_terminate (to execute the handler used by the termination), you can call quick_exit (see example # 2)

 // set_terminate example #include <iostream> // std::cerr #include <exception> // std::set_terminate #include <cstdlib> // std::abort void myterminate () { std::cerr << "terminate handler called\n"; abort(); // forces abnormal termination } int main (void) { std::set_terminate (myterminate); throw 0; // unhandled exception: calls terminate handler return 0; } 

Quick_exit / at_quick_exit example:

 /* at_quick_exit example */ #include <stdio.h> /* puts */ #include <stdlib.h> /* at_quick_exit, quick_exit, EXIT_SUCCESS */ void fnQExit (void) { puts ("Quick exit function."); } int main () { at_quick_exit (fnQExit); puts ("Main function: Beginning"); quick_exit (EXIT_SUCCESS); puts ("Main function: End"); // never executed return 0; } 

I'm not quite sure why quick_exit could be called, but it exists, and so I have to provide it with documentation (kindly provided by http://www.cplusplus.com/reference )

Alternatively, you can call at_exit as the equivalent of at_quick_exit.

Admittedly, I am not completely familiar with set_terminate and terminate, since I do not name them myself, but I would suggest that you could use quick_exit as a completion handler if you want; or custom (but please do not quote me on this).

0
source

In C ++, you can use exit (0) for example:

  switch(option){ case 1: //statement break; case 2: //statement exit(0); 
-1
source

Source: https://habr.com/ru/post/888140/


All Articles