4

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 :)

mzoz
  • 1,273
  • 1
  • 14
  • 28
  • 2
    possible duplicate of [How to quit a C++ program?](http://stackoverflow.com/questions/1116493/how-to-quit-a-c-program) – usr1234567 Sep 26 '15 at 13:06
  • If the problem is because of some data flow that you would like the user to be able to inspect, `std::abort()` may be a good idea, since it exits the process with a signal and may cause the host to create a core dump (making the situation debuggable in multiple ways). – Kerrek SB Sep 26 '15 at 13:06
  • C is not C++ is not C! Pick one! – too honest for this site Sep 26 '15 at 13:32

4 Answers4

7

Use

exit(1);

The number indicates the exit status. 0 is no failure, everything larger then 0 indicates an error.

usr1234567
  • 21,601
  • 16
  • 108
  • 128
5

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.

Community
  • 1
  • 1
Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
1

You can use the exit() function to terminate the process at any point during step1(), step2()... anywhere actually.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
1

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)

MByD
  • 135,866
  • 28
  • 264
  • 277