ES.86: Avoid modifying loop control variables inside the body of raw for-loops
ES.86:避免在基本for循环的循环体中修改循环控制变量
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(示例)
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.
//
}
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