tags:

views:

262

answers:

8

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

Something like python's sys.exit()?

+5  A: 
#include <cstdlib>
...
exit( exit_code );
PigBen
Using exit is not nice. It breaks all those RAII objects that we have spent time building correctly. It is a lot nicer to throw back to main. If on the other hand the program is corrupted you should really call std::terminate()
Martin York
@Martin, `std::terminate()` just calls `abort()` by default and `abort()` terminates the program without any destructors being called.
Whisty
@ Whisty: Yes std::terminate() is basically the C++ version of abort() (the difference being you can over-ride and thus to do a tiny amount of clean up (I emphasis **TINY**)). It is a call of last resort (like abort()). But at the point where data has been corrupted there is little point in unwinding the stack. Corrupt data means that nothing can be trusted (not even the stack unwinding). std::terminate() is what you call when you deliberately don't want the stack to unwind (because you can't trust it) and you want a core dump for dubuging.
Martin York
+4  A: 

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

Oli Charlesworth
Well, `std::exit` really :)
ephemient
A: 

exit(0); // at the end of main function before closing curly braces

krissam
Why? Returning from `main()` has the same effect as calling `exit()`, with the added benefit that any local variables in `main()` are destroyed.
James McNellis
+13  A: 

While you can call exit() (and may need to do so if your application encounters some fatal error), the cleanest way to exit a program is to return from main():

int main()
{
    // do whatever your program does

} // function returns and exits program

When you call exit(), objects with automatic storage duration (local variables) are not destroyed before the program terminates, so you don't get proper cleanup. Those objects might need to clean up any resources they own, persist any pending state changes, terminate any running threads, or perform other actions in order for the program to terminate cleanly.

James McNellis
And if you need to exit from deep within the program, a try/catch block in `main` might be preferable to `exit()`. That's really a holdover from C.
Mark Ransom
Remember that it is implementation defined weather the stack is unwound if an exception escapes main without being caught. So safest to catch all exceptions in main then rethrow. I say rethrow as some OSs(Windows) will catch an uncaught exception and do nice things for the developer (I am not sure if this applies only to debug).
Martin York
A: 

In main(), there is also:

return 0;
Moberg
Just `return 0;`? So, this would exit the program if I called `f()`? `int f() { return 0; }`
James McNellis
No - return 0 from main only. exit() works from anywhere
pm100
A: 

if you are in the main you can do:

return 0;  

or

exit(exit_code);

The exit code depends of the semantic of your code. 1 is error 0 e a normal exit.

In some other function of your program:

exit(exit_code)  

will exit the program.

Corgan
+3  A: 

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.

Bowie Owens
Note: `std::abort()` should be used for immediate termination. `std::terminate()` should only be used by the C++ exception handling facilities when exception handling fails; you shouldn't call it directly.
James McNellis
In my opinion, a `stop_now_t` exception type is an abuse of the exception system. Its use would indicate that you are using exceptions for normal control flow (which is usually bad). A function shouldn't throw an exception knowing that it will only be caught in `main()`; it should throw an exception assuming that it might be caught by any caller that can handle the exception.
James McNellis
James, you have got me on the std::terminate(). Yes, std::abort is a better choice. Whether an exception like stop_now_t is appropriate depends on how you have structured your algorithm. Granted in an example this simple it may be a bad way to do it. But I was just trying to illustrate how exceptions could be used.
Bowie Owens
What constitutes proper exception usage is a contentious issue; that was just my opinion; I'm sure if five other people here weigh in, we'll have at least eight different opinions :-) (Welcome to Stack Overflow; as a heads-up, if you put `@` before someone's username, that person will get a notification when they log in to see that they have a message)
James McNellis
+1  A: 

Allowing the execution flow to leave main by returning a value or allowing execution to reach the end of the function is the way a program should terminate except under unrecoverable circumstances. Returning a value is optional in C++, but I typically prefer to return EXIT_SUCCESS found in cstdlib (a platform-specific value that indicates the program executed successfully).

#include <cstdlib>

int main(int argc, char *argv[]) {
  ...
  return EXIT_SUCCESS;
}

If, however, your program reaches an unrecoverable state, it should throw an exception. It's important to realise the implications of doing so, however. There are no widely-accepted best practices for deciding what should or should not be an exception, but there are some general rules you need to be aware of.

For example, throwing an exception from a destructor is nearly always a terrible idea because the object being destroyed might have been destroyed because an exception had already been thrown. If a second exception is thrown, terminate is called and your program will halt without any further clean-up having been performed. You can use uncaught_exception to determine if it's safe, but it's generally better practice to never allow exceptions to leave a destructor.

While it's generally always possible for functions you call but didn't write to throw exceptions (for example, new will throw std::bad_alloc if it can't allocate enough memory), it's often difficult for beginner programmers to keep track of or even know about all of the special rules surrounding exceptions in C++. For this reason, I recommend only using them in situations where there's no sensible way for your program to continue execution.

#include <stdexcept>
#include <cstdlib>
#include <iostream>

int foo(int i) {
  if (i != 5) {
    throw std::runtime_error("foo: i is not 5!");
  }
  return i * 2;
}

int main(int argc, char *argv[]) {
  try {
    foo(3);
  }
  catch (const std::exception &e) {
    std::cout << e.what() << std::endl;
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}

exit is a hold-over from C and may result in objects with automatic storage to not be cleaned up properly. abort and terminate effectively causes the program to commit suicide and definitely won't clean up resources.

Whatever you do, don't use exceptions, exit, or abort/terminate as a crutch to get around writing a properly structured program. Save them for exceptional situations.

Sydius