[英]Quit the whole program early in C?
通常說我有一些函數step1
step2
...,它們被依次調用:
int main()
{
...
step1(); // something wrong detected and need to break out of the whole program
step2();
step3();
...
}
我如何才能從step1
突圍而跳過所有其余代碼以終止main()
函數?
目前,我只能想到將像bool isErr
這樣的全局變量設置為標志,以便
step1(); // error detected and isErr is set to 1 inside step1()
if (isErr)
return;
step2();
...
是否有更好或更規范的方法?
順便說一句,我聽說goto
不好,所以我將其丟棄:)
采用
exit(1);
數字表示退出狀態。 0表示沒有故障,大於0的所有值表示錯誤。
您可以在實際任何地方在step1()
, step2()
...期間的任何時候使用exit()
函數終止進程。
exit
將使程序無論您身在何處都將終止,但是在大多數情況下,這是一個壞主意,檢查函數的返回值並進行處理(例如,在您的情況下退出)是一種更干凈的方法(不需要全局變量)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.