293

I would like my C++ code to stop running if a certain condition is met, but I'm not sure how to do that. So just at any point if an if statement is true terminate the code like this:

if (x==1)
{
    kill code;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
The Nightman
  • 5,609
  • 13
  • 41
  • 74
  • 105
    Use proper logic. In `main()` use return, in functions use a proper return value or throw a proper Exception. **Do not** use `exit()`! – Kijewski May 15 '15 at 03:19
  • 2
    How drastic do you want the termination to be? You could use `abort()`, which might give you a core dump. You could use `assert(!(x == 1));` (inverting the logic of your `if` condition). There are advantages to that; you should get an error message that contains the asserted condition and the file name and line number. There are disadvantages too; you might get a core dump, and the exit isn't very controlled (but it wasn't with `abort()`, either). Or you could throw an exception. Or you return an error indication. – Jonathan Leffler May 15 '15 at 03:32
  • so i want the program to entirely terminate. as imallett posted below exit(-1) does what I want. But I dont undersand why it is dangerous to use that. – The Nightman May 15 '15 at 03:34
  • `return 0;` put that wherever you want within `int main()` and the program will immediately close. – Evan Carslake May 15 '15 at 03:39
  • 1
    @Kay why not implement the logic is another way: use a flag variable such as `bool continue_running = true` and have the loop depend on this state to continue running. This would be true under typical running conditions; however, when the condition to stop running is met, why not simply have the if statement be `continue_running = false;` which would stop the loop from running? It is typically a best practice to have a single return statement / return path in a routine, where possible, which also simplifies the code for anyone else who would use or review it later. – localhost May 15 '15 at 03:47
  • @localhost, using a flag is perfectly fine of course if your application happens to be a loop. Possibly even a tristate (do continue, finished, error case). – Kijewski May 15 '15 at 03:49
  • Except that a return from main is illogical, since main is the starting point of the program. – jamesqf May 15 '15 at 05:41
  • 6
    @JonathanLeffler: When compiled with `NDEBUG` defined, `assert` will likely become a no-op, so you shouldn't rely on it for more than detecing bugs. – MvG May 15 '15 at 07:36
  • 13
    @jamesqf: a `return` from `main()` is perfectly logical. It sets the exit code reported by the program to the operating system, which can be useful in many cases (if your program can be used as part of a larger process, for example). – AAT May 15 '15 at 09:03
  • This discussion has good info but i'm amazed that this Q is not a duplicate of something. See also this thread, which links to another thread discussing the same issue. : http://stackoverflow.com/questions/25141737/why-is-using-exit-considered-bad – Brandin May 15 '15 at 09:17
  • 11
    Interestingly this Q is a duplicate of this one from 5 years ago, whose accepted answer is quite different: http://stackoverflow.com/questions/1116493/how-to-quit-a-c-program I guess it took the community 5 years to learn that blindly calling std::exit might be bad? – Brandin May 15 '15 at 09:20
  • 2
    Graceful exit habit is very important, because your program is not The Universe. There are HDD data, there are another programs which talking with your's. You must love C++ destructors because they are most important Stroustrup' invention allowing to write large fast reliable programs. – Brian Cannard May 15 '15 at 17:08
  • @ AAT: So does calling exit set the exit code. Indeed, that could be why it's called the EXIT code, and not the return code :-) – jamesqf May 15 '15 at 17:29
  • @Kay: Does that advice about exit also apply to C? – Giorgi Moniava May 15 '15 at 21:22
  • @jamesqf calling `exit()` won't invoke destructors for stack objects while `return` will – chbaker0 May 16 '15 at 04:56
  • 1
    @Giorgi IMO in C it may be less of a problem, the patterns are different, most libraries set up a `std::at_exit` handler to perform cleanup on their stuff. The C standard library also guarantees cleanup on some of it's stuff during `std::exit` such as flushing/closing C streams properly. Memory allocated with _malloc_ mayn't be a problem as the OS will take care of it anyway, but I'm not certain, someone correct me if I'm wrong because I've never programmed on more restricted systems. – Denilson Amorim May 16 '15 at 05:02
  • @imallett, so? The newer other question has better answers than the older one. – Kijewski May 16 '15 at 12:05
  • 5
    Questions [Why is using `exit()` considered bad? – SO 25141737](http://stackoverflow.com/questions/25141737) and [How to quit a C++ program? – SO 1116493](http://stackoverflow.com/questions/1116493) are now closed as duplicates of this one. The first of those has a reference to 'Crash-only Software' that might be worth a look, if only to stimulate your thinking about how to write robust software. – Jonathan Leffler May 16 '15 at 16:58
  • Now this got pretty weird. One plain `exit` answer with 9 downvotes and another, even more plain, with 44 upvotes. – Denilson Amorim May 17 '15 at 18:50
  • I'm even more amazed by the question having so many upvotes... The accepted answer is very good, but the question itself is pretty much screaming for downvotes... – Franz Wurst May 18 '15 at 10:49
  • 1
    @jamesqf *"Except that a return from main is illogical, since main is the starting point of the program."* `main` is not the starting point of the program. The starting point of the program is long before `main` is called by the runtime. `main` is simply the starting point of *your own code*. Somewhere, in the bowels of the runtime, there exists code much like `int main_ret_val = main(); /* ... then we do some cleanup here ... */ /* once that is done: */ exit(main_ret_val);`. – user May 18 '15 at 12:27
  • @FranzWurst The question is on the hot network questions list. That probably explains a large fraction of the upvotes, as that tends to draw a lot of attention from across the network. – user May 18 '15 at 12:29

14 Answers14

475

There are several ways, but first you need to understand why object cleanup is important, and hence the reason std::exit is marginalized among C++ programmers.

RAII and Stack Unwinding

C++ makes use of a idiom called RAII, which in simple terms means objects should perform initialization in the constructor and cleanup in the destructor. For instance the std::ofstream class [may] open the file during the constructor, then the user performs output operations on it, and finally at the end of its life cycle, usually determined by its scope, the destructor is called that essentially closes the file and flushes any written content into the disk.

What happens if you don't get to the destructor to flush and close the file? Who knows! But possibly it won't write all the data it was supposed to write into the file.

For instance consider this code

#include <fstream>
#include <exception>
#include <memory>

void inner_mad()
{
    throw std::exception();
}

void mad()
{
    auto ptr = std::make_unique<int>();
    inner_mad();
}

int main()
{
    std::ofstream os("file.txt");
    os << "Content!!!";

    int possibility = /* either 1, 2, 3 or 4 */;
    
    if(possibility == 1)
        return 0;
    else if(possibility == 2)
        throw std::exception();
    else if(possibility == 3)
        mad();
    else if(possibility == 4)
        exit(0);
}

What happens in each possibility is:

  • Possibility 1: Return essentially leaves the current function scope, so it knows about the end of the life cycle of os thus calling its destructor and doing proper cleanup by closing and flushing the file to disk.
  • Possibility 2: Throwing a exception also takes care of the life cycle of the objects in the current scope, thus doing proper cleanup...
  • Possibility 3: Here stack unwinding enters in action! Even though the exception is thrown at inner_mad, the unwinder will go though the stack of mad and main to perform proper cleanup, all the objects are going to be destructed properly, including ptr and os.
  • Possibility 4: Well, here? exit is a C function and it's not aware nor compatible with the C++ idioms. It does not perform cleanup on your objects, including os in the very same scope. So your file won't be closed properly and for this reason the content might never get written into it!
  • Other Possibilities: It'll just leave main scope, by performing a implicit return 0 and thus having the same effect as possibility 1, i.e. proper cleanup.

But don't be so certain about what I just told you (mainly possibilities 2 and 3); continue reading and we'll find out how to perform a proper exception based cleanup.

Possible Ways To End

Return from main!

You should do this whenever possible; always prefer to return from your program by returning a proper exit status from main.

The caller of your program, and possibly the operating system, might want to know whether what your program was supposed to do was done successfully or not. For this same reason you should return either zero or EXIT_SUCCESS to signal that the program successfully terminated and EXIT_FAILURE to signal the program terminated unsuccessfully, any other form of return value is implementation-defined (§18.5/8).

However you may be very deep in the call stack, and returning all of it may be painful...

[Do not] throw an exception

Throwing an exception will perform proper object cleanup using stack unwinding, by calling the destructor of every object in any previous scope.

But here's the catch! It's implementation-defined whether stack unwinding is performed when a thrown exception is not handled (by the catch(...) clause) or even if you have a noexcept function in the middle of the call stack. This is stated in §15.5.1 [except.terminate]:

  1. In some situations exception handling must be abandoned for less subtle error handling techniques. [Note: These situations are:

[...]

when the exception handling mechanism cannot find a handler for a thrown exception (15.3), or when the search for a handler (15.3) encounters the outermost block of a function with a noexcept-specification that does not allow the exception (15.4), or [...]

[...]

  1. In such cases, std::terminate() is called (18.8.3). In the situation where no matching handler is found, it is implementation-defined whether or not the stack is unwound before std::terminate() is called [...]

So we have to catch it!

Do throw an exception and catch it at main!

Since uncaught exceptions may not perform stack unwinding (and consequently won't perform proper cleanup), we should catch the exception in main and then return a exit status (EXIT_SUCCESS or EXIT_FAILURE).

So a possibly good setup would be:

int main()
{
    /* ... */
    try
    {
        // Insert code that will return by throwing a exception.
    }
    catch(const std::exception&)  // Consider using a custom exception type for intentional
    {                             // throws. A good idea might be a `return_exception`.
        return EXIT_FAILURE;
    }
    /* ... */
}

[Do not] std::exit

This does not perform any sort of stack unwinding, and no alive object on the stack will call its respective destructor to perform cleanup.

This is enforced in §3.6.1/4 [basic.start.init]:

Terminating the program without leaving the current block (e.g., by calling the function std::exit(int) (18.5)) does not destroy any objects with automatic storage duration (12.4). If std::exit is called to end a program during the destruction of an object with static or thread storage duration, the program has undefined behavior.

Think about it now, why would you do such a thing? How many objects have you painfully damaged?

Other [as bad] alternatives

There are other ways to terminate a program (other than crashing), but they aren't recommended. Just for the sake of clarification they are going to be presented here. Notice how normal program termination does not mean stack unwinding but an okay state for the operating system.

  • std::_Exit causes a normal program termination, and that's it.
  • std::quick_exit causes a normal program termination and calls std::at_quick_exit handlers, no other cleanup is performed.
  • std::exit causes a normal program termination and then calls std::atexit handlers. Other sorts of cleanups are performed such as calling static objects destructors.
  • std::abort causes an abnormal program termination, no cleanup is performed. This should be called if the program terminated in a really, really unexpected way. It'll do nothing but signal the OS about the abnormal termination. Some systems perform a core dump in this case.
  • std::terminate calls the std::terminate_handler which calls std::abort by default.
Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
Denilson Amorim
  • 9,642
  • 6
  • 27
  • 31
  • 30
    This is quite informative: notably I never realised that throwing an exception that is not handled anywhere (for instance: some `new` throws `std::bad_alloc` and your program forgot to catch that exception anywhere) will **not** properly unwind the stack before terminating. This seems silly to me: it would have been easy to essentially wrap the call to `main` in a trivial `try{`-`}catch(...){}` block that would ensure stack unwinding is properly done in such cases, at no cost (by which I mean: programs not using this will pay no penalty). Is there any particular reason this is not done? – Marc van Leeuwen May 15 '15 at 08:49
  • 15
    @MarcvanLeeuwen one possible reason is debugging: you want to break into the debugger as soon as an unhandled exception is thrown. Unwinding the stack and doing cleanup would erase the context of what caused the crash that you want to debug. If no debugger is present it might be better to dump core so that postmortem analysis can be done. – Hugh Allen May 15 '15 at 10:31
  • 13
    Sometimes my browser bugs out (I blame flash) and consumes several gigabytes of RAM and my OS dumps pages on the hard-drive making everything slow. When I close the browser it does proper stack unwinding, meaning all those gigabytes of RAM are read from the hard-drive and copied to memory just to be released, which takes a minute or so. I so wish they had used `std::abort` instead so the OS can release all memory, sockets and file descriptors without swapping for a minute. – nwp May 15 '15 at 14:42
  • This answer is quite informative, but would be helped by citing *§3.6.1/4 [basic.start.init]* as well...as `std::exit()` not invoking the destructors of automatic objects is Standard-prescribed, but can be a problem if those destructors must manually clean up resources (such as lock files or temporary database records) – LThode May 15 '15 at 20:29
  • if I understood you correct this wikipedia article (http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization) is a little bit incorrect:"The destructors of both the lock and file objects are therefore guaranteed to be called when returning from the function, whether an exception has been thrown or not" -if exception is not caught as you say destructor might not get called right? – Giorgi Moniava May 15 '15 at 23:05
  • @Giorgi The destructor will be called. If it didn't, a lot of C++ programs would have flat out no exception safety. – Rapptz May 16 '15 at 06:47
  • @Rapptz: according to the link's explanation if exception is not caught it is implementation defined if destructor will be called isn't it? – Giorgi Moniava May 16 '15 at 09:15
  • 2
    @nwp, I understand the feeling. But killing instantly may corrupt files, not save my most recent tabs, etc :) – Paul Draper May 16 '15 at 21:42
  • 1
    @PaulDraper That could happen for so many other reasons. If a program is ever in a state where instantly killing the program would cause corrupt files or other loss of data that was supposed to be persistent, then the program is incorrectly designed. – kasperd May 17 '15 at 20:45
  • @kasperd, true, if the program is a database, or corrupts important data. Power loss can kill a program instantly. But if it is a more minor loss, that could be tolerable. – Paul Draper May 17 '15 at 21:49
  • 3
    @PaulDraper I would certainly not consider it tolerable if a browser couldn't restore the tabs I had open before a power loss. Of course if I had just opened a tab, and it hadn't had time to save it yet, it would be lost. But other than that, I say there's no excuse for losing it. – kasperd May 17 '15 at 21:57
  • 1
    @thelink2012 You may want to edit **Possibility 3** and mention explicitly (or refer to the latter paragraph) that stack unwinding is not guaranteed unless the exception is processed in a try/catch. You mention this after, but the summary is excellent and catches the reader's attention first. This issue may be confusing (I also had for a long time the impression that you don't need a try/catch block), and should be emphasized. Otherwise, a great answer! – vsoftco May 21 '15 at 02:30
  • 1
    catching exceptions in main is great except what about exceptions from other threads? – Inverse Jun 03 '15 at 21:34
  • 1
    See also my answer here: http://stackoverflow.com/a/25142157 If all that stack-unwinding only does things which **just don't matter anymore** when the process is shut down, avoiding them and not letting the user wait is *the right thing*. – Deduplicator Jul 19 '15 at 15:54
  • In the days of C89, return values from main were not portable. The value would simply be passed to the OS. Unix and DOS platforms expected 0 for success and anything else for failure. But VMS treated even exit statuses as failures and odd numbers as success. So `return 0` from main would report an access violation, and `return 1` indicated success--exactly the opposite of the intent. You might have expected `EXIT_SUCCESS` and `EXIT_FAILURE` to map to appropriate values when targeting VMS, but that wasn't the case. The only portable way exit with success was `exit(EXIT_SUCCESS)`. – Adrian McCarthy Jul 01 '23 at 06:40
  • Depending on the hosted implementation, calling exit may indeed run destructors for the globals and other statics since exit runs the functions registered with at_exit, which is exactly how some systems schedule destructors for statics. But automatic variables won't have their destructors run. – Adrian McCarthy Jul 01 '23 at 06:44
63

As Martin York mentioned, exit doesn't perform necessary clean-up like return does.

It's always better to use return in the place of exit. In case if you are not in main, wherever you would like to exit the program, return to main first.

Consider the below example. With the following program, a file will be created with the content mentioned. But if return is commented & uncommented exit(0), the compiler doesn't assure you that the file will have the required text.

int main()
{
    ofstream os("out.txt");
    os << "Hello, Can you see me!\n";
    return(0);
    //exit(0);
}

Not just this, Having multiple exit points in a program will make debugging harder. Use exit only when it can be justified.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Narendra N
  • 1,270
  • 1
  • 9
  • 14
  • 2
    What do you recommend to achieve this behavior in a little bit bigger program? How do you always return to main cleanly if somewhere deeper in the code an error condition is triggered that should exit the program? – Janusz Jul 13 '09 at 14:37
  • 5
    @Janusz, In that case, you can use/throw exceptions, if not return a pre-defined value i.e., have a return value from the function, like for example return 0 when successful, 1 in the case of failure, but continue execution, -1 in the case of failure & exit the program. Based the return value from the function, if that's a failure, just return from the main after performing any more clean-up activties. Finally, use exit judiciously, I doesn't mean to avoid it. – Narendra N Jul 14 '09 at 07:09
  • 1
    @NarendraN, "necessary cleanup" is vague - the OS will take care (Windows/Linux) that memory and file handles are properly released. As for the "missing" file output: If you insist that this could be a real problem, see http://stackoverflow.com/questions/14105650/how-does-stdflush-work If you have an error condition, proper logging tells you that your program reached an undefined state and you can set a breakpoint right before your logging point. How does that make debugging harder? – Markus Aug 01 '14 at 08:47
  • 2
    Note that this answer was merged from the question [How to quit a C++ program? – SO 1116493](http://stackoverflow.com/questions/1116493). This answer was written approximately 6 years before this question was asked. – Jonathan Leffler Jul 19 '15 at 19:32
  • 1
    for modern C++ use `return (EXIT_SUCCESS);` instead `return(0)` – Jonas Stein May 01 '19 at 19:00
40

Call the std::exit function.   

Otávio Décio
  • 73,752
  • 17
  • 161
  • 228
  • 2
    Which objects' destructors get called when you call that function? – Rob Kennedy Jul 12 '09 at 19:02
  • 38
    exit() does not return. So no stack unwinding can take place. Not even global objects do not get destroyed. But the functions registered with atexit() will be called. – Martin York Jul 12 '09 at 22:34
  • 18
    Please do not call `exit()` when your library code is running inside my host process - the latter will exit in the middle of nowhere. – sharptooth May 18 '15 at 07:18
  • 5
    Note that this answer was merged from the question [How to quit a C++ program? – SO 1116493](http://stackoverflow.com/questions/1116493). This answer was written approximately 6 years before this question was asked. – Jonathan Leffler Jul 19 '15 at 19:32
  • @MartinYork: Actually, global objects may be destroyed. Some implementations schedule destruction of globals and other statics using the at_exit mechanism. – Adrian McCarthy Jul 01 '23 at 06:47
23

People are saying "call exit(return code)," but this is bad form. In small programs it is fine, but there are a number of issues with this:

  1. You will end up having multiple exit points from the program
  2. It makes code more convoluted (like using goto)
  3. It cannot release memory allocated at runtime

Really, the only time you should exit the problem is with this line in main.cpp:

return 0;

If you are using exit() to handle errors, you should learn about exceptions (and nesting exceptions), as a much more elegant and safe method.

jkeys
  • 3,803
  • 11
  • 39
  • 63
  • 10
    In a multi-threaded environment, an exception thrown in a different thread will not be handled though main() -- some manual cross-thread communication is needed before the subordinate thread expires. – Steve Gilham Jul 22 '09 at 22:39
  • 3
    1. and 2. are up to the programmer, with proper logging this is not a problem since exeuction stops forever. As for 3: That is just plain wrong, the OS will free the memory - maybe excluding embedded devices/realtime, but if you're doing that, you probably know your stuff. – Markus Aug 01 '14 at 08:37
  • 1
    Note that this answer was merged from the question [How to quit a C++ program? – SO 1116493](http://stackoverflow.com/questions/1116493). This answer was written approximately 6 years before this question was asked. – Jonathan Leffler Jul 19 '15 at 19:32
  • 1
    If an error occurred, though, you shouldn't return 0. You should return 1 (or possibly some other value, but 1 is always a safe choice). – Kef Schecter Nov 20 '17 at 00:34
  • 1
    @Kef Schecter: "Always a safe choice" except on VMS. I think the standard now requires `return 0` from main to result in a normal (successful) exit status. But any other value may be passed as-is to the OS. On VMS, 1 is success. – Adrian McCarthy Jul 01 '23 at 06:51
  • @AdrianMcCarthy I stand corrected. I should have said EXIT_FAILURE. Hardly anybody bothers, though. – Kef Schecter Jul 04 '23 at 11:38
  • 1
    @Kef Schecter: Unfortunately that doesn't work on all implementations for VMS. EXIT_SUCCESS and EXIT_FAILURE do what you'd expect when provided as the argument in a call to exit, but returning either of those constants from main can give exactly the oppose result of what you'd want. Perhaps that's all been worked out since I last worked on VMS, but it was a significant portability problem once upon a time. – Adrian McCarthy Jul 05 '23 at 05:51
12

return 0; put that wherever you want within int main() and the program will immediately close.

Evan Carslake
  • 2,267
  • 15
  • 38
  • 56
  • the-nightman, @evan-carslake, and everyone else, I would also add that this SO [question #36707](http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement) gives a discussion as to whether a return statement should just occur anywhere in a routine. This is a solution; however, depending on the specific situation, I wouldn't say this is the best solution. – localhost May 15 '15 at 03:58
  • 1
    OP said nothing about this, so I think it is rather rash to assume the code was meant to be inside the function `main`. – Marc van Leeuwen May 15 '15 at 08:55
  • @localhost A return statement is completely optional in every situation, under any conditions. However, `int main()` is different. The program uses `int main()` to begin and end. There is no other way to do it. The program will run until you return true or false. Almost all of the time you will return 1 or true, to indicate the program has closed correctly (ex: might use false if you could not free memory or whatever reason.) Letting the program run itself finished is always a bad idea, example: `int main() { int x = 2; int foo = x*5; std::cout << "blah"; }` – Evan Carslake May 15 '15 at 15:28
  • @EvanCarslake Understood, if you noticed a comment I posted elsewhere for this question, I am familiar with this about `int main`; however, it is not always a good idea having multiple return statements in a main routine. One potential caveat is to improve code readability; however, using something like a boolean flag that changes state to prevent certain code sections of code from running in that application state. Personally, I find a common return statement makes most applications more readable. Lastly, questions about memory cleanup and closing I/O objects properly before the exit. – localhost May 15 '15 at 19:32
  • 2
    @EvanCarslake you don't return `true` from `main` to indicate a correct termination. You must return zero or `EXIT_SUCCESS` (or, if you want, `false`, which would be implicitly converted to zero) to indicate normal termination. To indicate failure you can return `EXIT_FAILURE`. Any other code meaning is implementation-defined (on POSIX systems it would mean actual error code). – Ruslan May 16 '15 at 19:05
  • @Ruslan yeah, my bad, I had that mixed up for some reason. – Evan Carslake May 16 '15 at 20:57
11

The program will terminate when the execution flow reaches the end of the main function.

To terminate it before then, you can use the exit(int status) function, where status is a value returned to whatever started the program. 0 normally indicates a non-error state

chrisbunney
  • 5,819
  • 7
  • 48
  • 67
  • 2
    Note that this answer was merged from the question [How to quit a C++ program? – SO 1116493](http://stackoverflow.com/questions/1116493). This answer was written approximately 6 years before this question was asked. – Jonathan Leffler Jul 19 '15 at 19:33
11

If you have an error somewhere deep in the code, then either throw an exception or set the error code. It's always better to throw an exception instead of setting error codes.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Jagannath
  • 3,995
  • 26
  • 30
  • 3
    Note that this answer was merged from the question [How to quit a C++ program? – SO 1116493](http://stackoverflow.com/questions/1116493). This answer was written approximately 6 years before this question was asked. – Jonathan Leffler Jul 19 '15 at 19:33
10

Either return a value from your main or use the exit function. Both take an int. It doesn't really matter what value you return unless you have an external process watching for the return value.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Goz
  • 61,365
  • 24
  • 124
  • 204
  • 5
    Note that this answer was merged from the question [How to quit a C++ program? – SO 1116493](http://stackoverflow.com/questions/1116493). This answer was written approximately 6 years before this question was asked. – Jonathan Leffler Jul 19 '15 at 19:33
10

Generally you would use the exit() method with an appropriate exit status.

Zero would mean a successful run. A non-zero status indicates some sort of problem has occurred. This exit code is used by parent processes (e.g. shell scripts) to determine if a process has run successfully.

shA.t
  • 16,580
  • 5
  • 54
  • 111
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • 1
    using exit MAY mean you have a design problem. If a program bheaves correctly it should just terminate when main `return 0;`. I assume `exit()` is like `assert(false);` and so should be used only in development to early catch problems. – CoffeDeveloper May 18 '15 at 10:10
  • 3
    Note that this answer was merged from the question [How to quit a C++ program? – SO 1116493](http://stackoverflow.com/questions/1116493). This answer was written approximately 6 years before this question was asked. – Jonathan Leffler Jul 19 '15 at 19:33
7

Beyond calling exit(error_code) - which calls atexit handlers, but not RAII destructors, etc. - more and more I am using exceptions.

More and more my main program looks like

int main(int argc, char** argv) 
{
    try {
        exit( secondary_main(argc, argv );
    }
    catch(...) {
        // optionally, print something like "unexpected or unknown exception caught by main"
        exit(1);
    }
}

where secondary_main in where all the stuff that was originally is put -- i.e. the original main is renamed secondary_main, and the stub main above is added. This is just a nicety, so that there isn't too much code between the tray and catch in main.

If you want, catch other exception types.
I quite like catching string error types, like std::string or char*, and printing those in the catch handler in main.

Using exceptions like this at least allows RAII destructors to be called, so that they can do cleanup. Which can be pleasant and useful.

Overall, C error handling - exit and signals - and C++ error handling - try/catch/throw exceptions - play together inconsistently at best.

Then, where you detect an error

throw "error message"

or some more specific exception type.

Krazy Glew
  • 7,210
  • 2
  • 49
  • 62
  • By the way: I am well aware that using a data type like string, which may involve dynamic memory allocation, is not a good idea in or around an exception handler for exceptions that may be related to running out of memory. C-style string constants are not a problem. – Krazy Glew Aug 04 '14 at 01:45
  • 2
    There's no point in calling `exit` in your program. Since you're in `main`, you can just `return exitCode;`. – Ruslan May 18 '15 at 12:53
0

If the condition I'm testing for is really bad news, I do this:

*(int*) NULL= 0;

This gives me a nice coredump from where I can examine the situation.

dodo
  • 162
  • 5
  • 4
    This may well be optimized out, since it causes undefined behavior. In fact, the whole branch of execution having such a statement can be wiped out by the compiler. – Ruslan Mar 17 '17 at 15:00
  • Being optimised out can be circumvented though. It's an interesting approach - has this proven to be useful in the field? – Den-Jason Dec 09 '20 at 11:33
  • If you put the line that generates a crash into an external function, the call to the external function cannot elided or inlined. As long as the function itself is not optimized, this works. OSes often provide an API to force a crash specifically because it's often safer to crash then to try to clean up after detecting that the program is in a bad state. – Adrian McCarthy Jul 01 '23 at 06:58
-2

If your if statement is in Loop You can use

break;

If you want to escape some code & continue to loop Use :

continue;

If your if statement is not in Loop You can use :

return 0 or exit();

Akshay
  • 24
  • 1
  • 5
-3

Dude... exit() function is defined under stdlib.h

So you need to add a preprocessor.

Put include stdlib.h in the header section

Then use exit(); wherever you like but remember to put an interger number in the parenthesis of exit.

for example:

exit(0);
Tim Penner
  • 3,551
  • 21
  • 36
-5

To break a condition use the return(0);

So, in your case it would be:

    if(x==1)
    {
        return 0;
    }
Lavender
  • 13
  • 4