cterminate

Quit the whole program early in C?


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


Solution

  • 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.