管理C程序资源的最佳方法是什么?是使用嵌套的if结构还是使用goto语句?
我知道有很多关于goto语句的禁忌。不过,我认为本地资源的清理是有道理的。我提供了两个样品。一个比较嵌套的if结构,另一个使用goto语句。我个人认为goto语句可以使代码更容易阅读。对于那些可能认为嵌套if提示结构更好的人来说,想象一下如果数据类型不是char*,比如句柄。我觉得嵌套的if结构将失去对一系列CreateFile函数或任何其他需要大量参数的函数的控制。
这个文章演示了本地goto语句为C代码创建RAII。代码很整洁,易于遵循。假设这是一系列嵌套的if语句。
我理解goto在许多其他语言中是禁忌的,因为它们存在其他控制机制,如try/等,但是在C语言中似乎是合适的。
#include <stdlib.h>
#define STRING_MAX 10
void gotoExample()
{
char *string1, *string2, *string3, *string4, *string5;
if ( !(string1 = (char*) calloc(STRING_MAX, sizeof(char))) )
goto gotoExample_string1;
if ( !(string2 = (char*) calloc(STRING_MAX, sizeof(char))) )
goto gotoExample_string2;
if ( !(string3 = (char*) calloc(STRING_MAX, sizeof(char))) )
goto gotoExample_string3;
if ( !(string4 = (char*) calloc(STRING_MAX, sizeof(char))) )
goto gotoExample_string4;
if ( !(string5 = (char*) calloc(STRING_MAX, sizeof(char))) )
goto gotoExample_string5;
//important code goes here
gotoExample_string5:
free(string4);
gotoExample_string4:
free(string3);
gotoExample_string3:
free(string2);
gotoExample_string2:
free(string1);
gotoExample_string1:
}
void nestedIfExample()
{
char *string1, *string2, *string3, *string4, *string5;
if (string1 = (char*) calloc(STRING_MAX, sizeof(char)))
{
if (string2 = (char*) calloc(STRING_MAX, sizeof(char)))
{
if (string3 = (char*) calloc(STRING_MAX, sizeof(char)))
{
if (string4 = (char*) calloc(STRING_MAX, sizeof(char)))
{
if (string5 = (char*) calloc(STRING_MAX, sizeof(char)))
{
//important code here
free(string5);
}
free(string4);
}
free(string3);
}
free(string2);
}
free(string1);
}
}
int main(int argc, char* argv[])
{
nestedIfExample();
gotoExample();
return 0;
}我还想引用Linux关于Linux语句的话。
有时结构是不好的,并进入了道路,而使用一个"goto“就更清楚了。 例如,有不嵌套的条件是很常见的。 在这种情况下,您有两种可能性
Pascal语言是后一个问题的一个主要例子。因为它没有“中断”语句,所以循环在(传统的) Pascal中常常看起来像完全的狗屎,因为你必须添加完全任意的逻辑才能说“我现在就完了”。
goto是否可用于资源管理?我应该使用嵌套的if语句还是有更好的方法?
更新: C语言中的Gotos示例
发布于 2010-11-30 18:25:03
对我来说,我更喜欢这种风格的goto错误处理。将Nick D的代码片段更进一步,它使用一个通用的goto标签来进行错误处理。
void gotoExample()
{
char *string1, *string2, *string3, *string4, *string5;
string1 = string2 = string3 = string4 = string5 = NULL;
if ( !(string1 = (char*) calloc(STRING_MAX, sizeof(char))) )
goto HANDLE_ERROR;
if ( !(string2 = (char*) calloc(STRING_MAX, sizeof(char))) )
goto HANDLE_ERROR;
if ( !(string3 = (char*) calloc(STRING_MAX, sizeof(char))) )
goto HANDLE_ERROR;
if ( !(string4 = (char*) calloc(STRING_MAX, sizeof(char))) )
goto HANDLE_ERROR;
if ( !(string5 = (char*) calloc(STRING_MAX, sizeof(char))) )
goto HANDLE_ERROR;
//important code goes here
HANDLE_ERROR:
if (string5)
free(string5);
if (string4)
free(string4);
if (string3)
free(string3);
if (string2)
free(string2);
if (string1)
free(string1);
}https://stackoverflow.com/questions/4148838
复制相似问题