gpt4 book ai didi

c - 最好返回 (EXIT_FAILURE) 到 main 或退出 (EXIT_FAILURE) 函数?

转载 作者:行者123 更新时间:2023-12-04 12:52:32 25 4
gpt4 key购买 nike

我有一个关于 c 中正确的程序结构的基本问题。

假设我的主要功能调用其他几个功能来配置特定的硬件(如以太网卡),并且这些功能中的每一个都调用更基本的功能来处理该以太网卡上更具体的配置。

下层函数都有返回值,说明它们是否成功完成。继续这种范式一直回到 main 是否最合适?

例如,如果我的一个较低级别的功能失败,我应该执行以下操作吗?:

check its return value --> return to calling function --> check its return value --> return to calling function ... 

一路回到主线?

或者让 main 假设一切正常(不考虑它调用的函数的返回值)并返回 0 是否更有意义?然后从较低级别的函数调用 exit(EXIT_FAILURE)?

非常感谢您的帮助。

最佳答案

对于学术水平的申请,我觉得不重要。 .但是,对于生产(企业)应用程序,我(30 年)的经验是:

1)  Never call exit() unless it's a last resort, where the user needs to 
contact the application developer to resolve an unanticipated condition.

2) In order to ensure maintainability, functions should not contain more
than one return statement.

我制作的所有功能(用于企业生产环境)都具有类似的流程:

int SomeEnterpriseQualityFunction(
SOME_TYPE1_T I__someValueBeingPassedIntoTheFunction,
...
SOME_TYPE2_T *IO_someValueBeingModifiedByTheFunction,
...
SOME_TYPE3_T **_O_someValueBeingReturnedByTheFunction
)
{
int rCode=0;
int someFileHandle=(-1);
void *someMemory = NULL;
SOME_TYPE3_T *someValueBeingReturnedByTheFunction=NULL;


/* Validate user input parameters */
if( /*I__someValueBeingPassedIntoTheFunction is out of range */)
{
rCode=ERANGE;
goto CLEANUP;
}

if( NULL == IO_someValueBeingModifiedByTheFunction )
{
rCode=EINVAL;
goto CLEANUP;
}

/* Acquire resources */
someFileHandle=open(/*someFileName, mode, etc.*/);
if((-1) == someFileHandle)
{
rCode=errno;
goto CLEANUP;
}

someMemory=malloc(/* bytesToMalloc */);
if(NULL == someMemory)
{
rCode=ENOMEM;
goto CLEANUP;
}

/* Actual work done here. */
....
if(/* Successfully finished work at this point... */)
goto RESULT;
...
...

/* Return results to caller here. */
RESULT:
if(_O_someValueBeingReturnedByTheFunction);
{
*_O_someValueBeingReturnedByTheFunction = someValueBeingReturnedByTheFunction;
someValueBeingReturnedByTheFunction = NULL;
}

/* Release acquired resources. */
CLEANUP:
if(someValueBeingReturnedByTheFunction)
{
int rc= /* Clean-up someValueBeingReturnedByTheFunction related resources,
since the caller didn't need it. */
if(0==rCode)
rCode=rc;
}

if(someMemory)
free(someMemory);

if((-1) != someFileHandle)
{
if((-1) == close(someFileHandle) && 0 == rCode)
rCode=rc;
}

return(rCode);
}

而且,无论您的讲师对 goto 怎么说,当以这种方式用于错误处理时,它们远非“邪恶”。

关于c - 最好返回 (EXIT_FAILURE) 到 main 或退出 (EXIT_FAILURE) 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23138963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com