C++中避免使用goto语句​的原因是什么

发布时间:2021-07-30 16:15:55 作者:Leah
来源:亿速云 阅读:152

这期内容当中小编将会给大家带来有关C++中避免使用goto语句的原因是什么,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

Reason(原因)

Readability, avoidance of errors. There are better control structures for humans; goto is for machine generated code.

可读性,避免错误。存在另外的更好的代码结构可用。

Exception(例外)

Breaking out of a nested loop. In that case, always jump forwards.

从嵌套循环中跳出。这种情况下,总是向前(代码执行角度的向前,译者注)跳。

for (int i = 0; i < imax; ++i)
   for (int j = 0; j < jmax; ++j) {
       if (a[i][j] > elem_max) goto finished;
       // ...
   }
finished:
// ...

Example, bad(反面示例)

There is a fair amount of use of the C goto-exit idiom:

存在相当数量的使用goto-exit惯用法的C代码。

void f()
{
   // ...
       goto exit;
   // ...
       goto exit;
   // ...
exit:
   // ... common cleanup code ...
}

This is an ad-hoc simulation of destructors. Declare your resources with handles with destructors that clean up. If for some reason you cannot handle all cleanup with destructors for the variables used, consider gsl::finally() as a cleaner and more reliable alternative to goto exit。

这是析构函数特别合适的使用场景。定义资源管理类,在它的析构函数中执行清除动作。如果由于某种原因,析构函数不能在所有情况下中实现完全地清除,考虑使用gsl::finally作为清除器和goto的更可靠代替手段。

Enforcement(实施建议)

上述就是小编为大家分享的C++中避免使用goto语句的原因是什么了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. PHP语法中goto 语句如何使用
  2. PHP中goto语句使用案例

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:C++中避免使用do语句的原因是什么

下一篇:C++中怎么使用async启动并发任务

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》