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

面向对象思考

共 699字,需浏览 2分钟

 ·

2020-06-01 23:21

9706fffe6386206f384d5651cf44b347.webp

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 loop
for (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 << '\n';
}

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




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

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

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


浏览 16
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报