Reputation: 1353
Generally say I have some functions step1
step2
... and they are called successively:
int main()
{
...
step1(); // something wrong detected and need to break out of the whole program
step2();
step3();
...
}
How can I break out from step1
and skip all the rest of code to terminate main()
function?
Currently I can only think of setting a global variable like bool isErr
as a flag so that
step1(); // error detected and isErr is set to 1 inside step1()
if (isErr)
return;
step2();
...
Are there better or more 'canonical' approaches?
BTW I've heard that goto
is bad so I discard it :)
Upvotes: 5
Views: 24707
Reputation: 154562
Call exit(int status)
anywhere in code.
Given various answers' discussions about status
, let us look at the spec:
Finally, control is returned to the host environment.
If the value ofstatus
is zero orEXIT_SUCCESS
, an implementation-defined form of the status successful termination is returned.
If the value ofstatus
isEXIT_FAILURE
, an implementation-defined form of the status unsuccessful termination is returned.
Otherwise the status returned is implementation-defined.
C11 §7.22.4.4 5
So better to call as exit(0)
, exit(EXIT_SUCCESS)
, exit(EXIT_FAILURE)
unless you clearly understand and have some advanced requirements.
Upvotes: 0
Reputation: 23461
Use
exit(1);
The number indicates the exit status. 0 is no failure, everything larger then 0 indicates an error.
Documentation at cppreference.com
Upvotes: 9
Reputation: 28685
One option is to check return value of your step1()
function and if it is error, just use for example return 1
in main
. Using return
(with appropriate status code) from main
to finish the program is the preferred way in C++.
Other option is exit
. The point is you can call it anywhere in the code. However, in C++ exit
is not recommended that much. Regarding C, there is a question here which discusses whether using exit
in C is a good idea or not.
Upvotes: 6
Reputation: 137442
exit
will terminate the program from wherever you are, but in most cases this is a bad idea, checking the return value of a function and handling (e.g. exit in your case) is a cleaner way to do it (no need for globals)
Upvotes: 1
Reputation: 145307
You can use the exit()
function to terminate the process at any point during step1()
, step2()
... anywhere actually.
Upvotes: 2