前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.86:避免在基本for循环的循环体中修改循环控制变量​

C++核心准则ES.86:避免在基本for循环的循环体中修改循环控制变量​

作者头像
面向对象思考
发布2020-06-11 16:27:58
1.7K0
发布2020-06-11 16:27:58
举报

ES.86: Avoid modifying loop control variables inside the body of raw for-loops

ES.86:避免在基本for循环的循环体中修改循环控制变量

Reason(原因)

The loop control up front should enable correct reasoning about what is happening inside the loop. Modifying loop counters in both the iteration-expression and inside the body of the loop is a perennial source of surprises and bugs.

外在的循环控制方式应该能够让人正确的推测循环内部正在发生什么。无论在迭代表达式中还是环体内修改循环计数都会增加理解难度甚至引发错误。

Example(示例)

代码语言:javascript
复制
for (int i = 0; i < 10; ++i) {
    // no updates to i -- ok
}

for (int i = 0; i < 10; ++i) {
    //
    if (/* something */) ++i; // BAD
    //
}

bool skip = false;
for (int i = 0; i < 10; ++i) {
    if (skip) { skip = false; continue; }
    //
    if (/* something */) skip = true;  // Better: using two variables for two concepts.
    //
}
Enforcement(实施建议)

Flag variables that are potentially updated (have a non-const use) in both the loop control iteration-expression and the loop body.

标记(循环,译者注)变量可能被修改(非常量参数使用)的情况,包含在迭代表达式中和循环体内部两种情况。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es86-avoid-modifying-loop-control-variables-inside-the-body-of-raw-for-loops

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-06-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
    • Enforcement(实施建议)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档