How to exit outside of a function ?

How to exit outside of a function ? Does exit(0) do that ?

1
2
3
4
5
void check_enpoint(int row, int col){
	if(board[row][col] == position::wall){
		exit(0);    // ?
	}
}


Just to make sure, break only exits outside of the if statement and a loop, right ? So in order to exit outside of a function, exit is more helpful ? Does it have a header name ? Is there a better method I can use ?
Can you be more precise about what it is that you want to do, please?

Are you talking about:

(a) making the program quit completely? If so, then exit() is one way to do that - although not always the best way.

(b) returning from a function, passing control back to the code that originally called the function, and carrying on from there? If so, then you use return.

(c) something else?
@MikeyBoy, I am making a board game which has corners represented as walls. Thus, when the for loops run through the board and they reach the wall, then I want my function to quit.


Question: So exit() exits completely out of the program, is there any better way ?
Question: Can a void function use return; to exit outside of a function?
Last edited on
yes.
void foo()
{
if(something)
return; //no value to return, just empty statement.
other things
if(other)
return;
more
//return implicit here, don't need.
}
So exit() exits completely out of the program, is there any better way ?

Almost certainly, yes. If you must quit and for whatever reason you cannot reliably reach main to return normally, throw an exception.

exit() introduces a hidden control path which terminates your program without destroying objects with automatic storage duration. This means that all of the resources you own in an automatic context (i.e., most of them) will simply leak, no matter what you do. More importantly, if your destructors do real work, they will simply be skipped, and code that you could otherwise guarantee would run wouldn't.

If you need to just transfer control elsewhere (give up) and simply returning is not feasible, then throw and optionally catch an exception. The stack unwinding that takes place as result of an exception (almost*) guarantees the destruction of automatic objects.

exit() makes more sense in the context of C programs, especially in combination with careful use of atexit() to release resources. Such a C++ program would be very unidiomatic in most (but not all) cases.

*almost, because the destructor can technically throw too. Throwing from a destructor is usually a bad idea.
Last edited on
Topic archived. No new replies allowed.