簡體   English   中英

如果函數返回錯誤,C編程將從主程序退出

[英]C programming exit from main if function return error

請看這個:

int f();
int g();

int main()
{
   f(); 
   g(); 

   return 0;
}

int f()
{
   // In case of fail
   return 1;
}

int g()
{
   return 0;
}

所以,如果我有一個errorf()我怎么能立即退出main沒有運行g()並返回0main

正確的做法是什么?

您可以從應用程序退出,如下所示:

int main()
{
  if (f())//if statement does not require `}` if it has only one statement. Here it is only `exit(1)` statement.
    exit(1);// error exit, you can use return 1; as well. Because here f() returns 1
  g();
  exit(0);  // correct execution exit. You can use return 0; as well.
}

現在,您可以檢查退出狀態,如下所示:-

UNIX / LINUX echo $?

WINDOWS echo %ERRORLEVEL%

int f();
int g();

int main()
{
  int value;
   if(!f()){

 return 0;
 }else{
 value= g();
    } 

 return value;
 }

int f()
 {

   if(stat=='correct'){
    // In case of success
   return 1;
  }
   else{ // In case of fail
    return 0;}
  } 

  int g()
 {
    if(stat=='correct'){
    // In case of success
   return 1;
  }
    else{ // In case of fail
    return 0;}
  }

您可以這樣操作:

int main()
{
   if(!f()){
     return 0;
   }else{
     g()
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM