簡體   English   中英

C 中 function 中 exit() 和 return 之間的最佳實踐是什么

[英]What is the best practice between exit() and return in function in C

你能告訴我在這個例子中使用 exit() in a function 還是 return 更好嗎?

#include <stdio.h>
#include <stdlib.h>

void function(char *);
int function2(char *);

int main(void)
{
        char *p;
        function(p);
        if(function2(p) < 0)
                exit(EXIT_FAILURE);

        return EXIT_SUCCESS;
}

void function(char *p)
{
        if(p == NULL)
                exit(EXIT_FAILURE);
}

int function2(char *p)
{
        if(p == NULL)
                return -1;
        return 0;
}

我發現當你有幾個嵌套函數時使用 return 會使代碼的可讀性降低,因為你必須 go 回到 main 才能退出。

但是我發現在有返回值的單元測試中測試它的功能更容易。

我發現當你有幾個嵌套函數時使用 return 會使代碼的可讀性降低,因為你必須 go 回到 main 才能退出。

但是我發現在有返回值的單元測試中測試它的功能更容易。

是的,這涉及到相互沖突的優先事項,而且這兩個並不是唯一的優先事項。 例如,如果所討論的 function 用於可重用庫,則在檢測到錯誤條件時退出程序可能不是可行的行為。 另一方面,如果在多線程程序中檢測到需要立即無條件終止,那么exit()是實現它的最干凈的可用方法之一。 清單從那里繼續。

但是, exit() ing 是不可恢復的,因此任何執行它的 function 都必須確保在這種情況下這樣做是正確的。 因此,我傾向於說雖然最佳方法因情況而異,但它強烈傾向於返回錯誤指示器或以其他記錄在案的方式發出錯誤信號,而不是調用exit()或另一個 function ( _exit() , abort() , ...) 終止程序。

您的問題(“C 中 function 中 exit() 和 return 之間的最佳實踐是什么”)非常籠統,答案要么是“它取決於...”,要么是關於 C 函數的教程。

然而,看看你的例子,以及你用“指針”標記問題的事實,讓我覺得你真的很想知道函數應該如何處理無效輸入。

不要對無效輸入使用 exit,有更好的選擇。 考慮使用斷言或異常(如果您的編譯器支持異常),這兩種選擇都會為您提供有關錯誤是什么以及發生位置的信息。

我無法憑空給你一個完整的答案,但我處理錯誤(包括無效輸入)的方法通常是這樣做的:

If the error can only be produced by a bug in the program then
 Report the error giving as much information as possible to help fix the bug,
 and then stop the program.
Else
 The function that detected the error should, depending on the error,
 either return an error code to the function that called it
 or treat the error as if it was produced by a bug.
 When a function calls a function, and gets an error code, it can, depending on the error code,
 either handle the error
 or treat the error as if it was produced by a bug.

暫無
暫無

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

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