其他
goto语句对与错
The following article is from 二进制人生 Author 二进制人生
很容易把逻辑弄乱,增加理解难度,goto是可以实现无条件跳转的,一旦跳转,就忽略很前面很多代码,特别是在一些逻辑复杂的地方使用,会很容易出问题。所以goto能不用就不用,特别对于新手,尽量避讳。
优点:
方便处理异常情况,特别是内存等系统资源的释放。很多大型项目,开源项目,包括Linux内核,都会使用goto来处理异常情况。
int module_init()
{
char *pdate = (char *)malloc(100);
if(pdate == NULL)
return -1;
char *pdate2 = (char *)malloc(100);
if(pdate2 == NULL)
return -1;
free(pdate);
free(pdate2);
......
}
goto实现代码
int module_init()
{
char *pdate = (char *)malloc(100);
if(pdate == NULL)
goto err;
char *pdate2 = (char *)malloc(100);
if(pdate2 == NULL)
goto err;
free(pdate);
free(pdate2);
......
err://统一的出错处理
if(pdate != NULL)
free(pdate);
if(pdate2!= NULL)
free(pdate2);
return -1;
}
if(pdate == NULL)
goto err1;
...
if(pdate2 == NULL)
goto err2;
...
err1:
free(pdate);
err2:
free(pdate2);
...
总结:存在即合理,好坏取决于如何使用。
-END-
来源 | 二进制人生
作者 | 二进制人生
| 整理文章为传播相关技术,版权归原作者所有 |
| 如有侵权,请联系删除 |
【3】C语言函数指针之回调函数