简体   繁体   中英

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

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.

Use

exit(1);

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

您可以在实际任何地方在step1()step2() ...期间的任何时候使用exit()函数终止进程。

exit将使程序无论您身在何处都将终止,但是在大多数情况下,这是一个坏主意,检查函数的返回值并进行处理(例如,在您的情况下退出)是一种更干净的方法(不需要全局变量)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM