循环初始化表达式_C++核心准则ES.74:尽量在循环变量初始化表达式中定义循环变量?...

87aa18cc49a13ca1d629080d949fbab2.png

ES.74: Prefer to declare a loop variable in the initializer part of a for-statement

ES.74:尽量在循环变量初始化表达式中定义循环变量

Reason(原因)

Limit the loop variable visibility to the scope of the loop. Avoid using the loop variable for other purposes after the loop.

将循环变量的作用域限制在循环之内。避免在循环之后将循环变量用于其他目的。

Example(示例)

for (int i = 0; i < 100; ++i) {   // GOOD: i var is visible only inside the loop    // ...}

Example, don't(反面示例)

int j;                            // BAD: j is visible outside the loopfor (j = 0; j < 100; ++j) {    // ...}// j is still visible here and isn't needed

See also: Don't use a variable for two unrelated purposes

参见:不用将变量用于两个不同的目的。

Example(示例)

for (string s; cin >> s; ) {    cout << s << '';}

Enforcement(实施建议)

Warn when a variable modified inside the for-statement is declared outside the loop and not being used outside the loop.

如果发现一个变量在for语句外部定义,在循环内部被修改,同时没有在循环外没有被使用的情况,发出警告。

Discussion: Scoping the loop variable to the loop body also helps code optimizers greatly. Recognizing that the induction variable is only accessible in the loop body unblocks optimizations such as hoisting, strength reduction, loop-invariant code motion, etc.

讨论:将循环变量的作用域限制在循环体之内非常有利于代码优化。需要认识到:只在循环体内部才是可访问的归纳变量是很多优化的必要条件:变量提升,强度削减,循环不变代码外提等。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es74-prefer-to-declare-a-loop-variable-in-the-initializer-part-of-a-for-statement


觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

dc37d5b07e119f9a33e0d3b1607e7e00.png
表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页