繁体   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