How do I make a C++ console program exit?

前端 未结 13 2313
执笔经年
执笔经年 2020-12-03 16:43

Is there a line of code that will terminate the program?

Something like python\'s sys.exit()?

相关标签:
13条回答
  • 2020-12-03 17:11

    In main(), there is also:

    return 0;
    
    0 讨论(0)
  • 2020-12-03 17:16

    There are several ways to cause your program to terminate. Which one is appropriate depends on why you want your program to terminate. The vast majority of the time it should be by executing a return statement in your main function. As in the following.

    int main()
    {
         f();
         return 0;
    }
    

    As others have identified this allows all your stack variables to be properly destructed so as to clean up properly. This is very important.

    If you have detected an error somewhere deep in your code and you need to exit out you should throw an exception to return to the main function. As in the following.

    struct stop_now_t { };
    void f()
    {
          // ...
          if (some_condition())
               throw stop_now_t();
          // ...
    }
    
    int main()
    {
         try {
              f();
         } catch (stop_now_t& stop) {
              return 1;
         }
         return 0;
     }
    

    This causes the stack to be unwound an all your stack variables to be destructed. Still very important. Note that it is appropriate to indicate failure with a non-zero return value.

    If in the unlikely case that your program detects a condition that indicates it is no longer safe to execute any more statements then you should use std::abort(). This will bring your program to a sudden stop with no further processing. std::exit() is similar but may call atexit handlers which could be bad if your program is sufficiently borked.

    0 讨论(0)
  • 2020-12-03 17:16

    simple enough..

    exit ( 0 ); }//end of function

    Make sure there is a space on both sides of the 0. Without spaces, the program will not stop.

    0 讨论(0)
  • 2020-12-03 17:18

    Yes! exit(). It's in <cstdlib>.

    0 讨论(0)
  • 2020-12-03 17:19
    else if(Decision >= 3)
        {
    exit(0);
        }
    
    0 讨论(0)
  • 2020-12-03 17:20

    This SO post provides an answer as well as explanation why not to use exit(). Worth a read.

    In short, you should return 0 in main(), as it will run all of the destructors and do object cleanup. Throwing would also work if you are exiting from an error.

    0 讨论(0)
提交回复
热议问题