开发者

How to exit program execution in C++?

Which function is used in C++ stdlib to exit from progra开发者_如何学运维m execution with status code?

In Java, there's:

System.exit(0)


Assuming you only have 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);
}

Output:

Hello, World!

The return(0); can be placed anywhere you like - it'll end int main(), and hence your program.


Alternatively, you can call exit(EXIT_SUCCESS); or exit(EXIT_FAILURE); from anywhere 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;
}


In addition to the other responses you can also invoke abort, terminate, quick_exit (exits without calling destructors, deallocating etc; hence the name)

terminate calls abort by default but can call any terminate handler you set.

Example usage of abort and set_terminate (to se the handler used by terminate), quick_exit can be called (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 entirely certain why one would call quick_exit but it exists and thus I should provide documentation for it (courtesy of http://www.cplusplus.com/reference )

Additionally one can call at_exit as the equivalent of at_quick_exit.

Admittedly I am not all that familiar with set_terminate and terminate as I don't call them myself, but I would guess you could use quick_exit as a terminate handler if you wanted; or a custom one (but please don't quote me on that).


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜