ES.77:循环中尽量少用break和continue
In a non-trivial loop body, it is easy to overlook a break or a continue.
A break in a loop has a dramatically different meaning than a break in a switch-statement (and you can have switch-statement in a loop and a loop in a switch-case).
在不规整的循环体中,很容易忽略掉break和continue。循环中的break和switch语句中的break存在显著的不同(同时你还可以将在循环体内放入switch语句或者在switch语句中放入循环。)
Example(示例)
switch(x) {
case 1 :
while (/* some condition */) {
//...
break;
} //Oops! break switch or break while intended?
case 2 :
//...
break;
}
Alternative(可选项)
Often, a loop that requires a break is a good candidate for a function (algorithm), in which case the break becomes a return.
需要break的循环通常很适合做成函数(算法),这是break可以变成return。
//Original code: break inside loop
void use1()
{
std::vector vec = {/* initialized with some values */};
T value;
for (const T item : vec) {
if (/* some condition*/) {
value = item;
break;
}
}
/* then do something with value */
}
//BETTER: create a function and return inside loop
T search(const std::vector &vec)
{
for (const T &item : vec) {
if (/* some condition*/) return item;
}
return T(); //default value
}
void use2()
{
std::vector vec = {/* initialized with some values */};
T value = search(vec);
/* then do something with value */
}
Often, a loop that uses continue can equivalently and as clearly be expressed by an if-statement.
通常,使用continue的循环可以等价地,清晰地表示为if语句。
for (int item : vec) { //BAD
if (item%2 == 0) continue;
if (item == 5) continue;
if (item > 10) continue;
/* do something with item */
}
for (int item : vec) { //GOOD
if (item%2 != 0 && item != 5 && item <= 10) {
/* do something with item */
}
}
Note(注意)
If you really need to break out a loop, a break is typically better than alternatives such as modifying the loop variable or a goto:
如果你确实需要终端一个循环,break通常会优于修改循环变量或goto语句。
Enforcement(实施建议)
???
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es77-minimize-the-use-of-break-and-continue-in-loops
新书介绍
以下是本人3月份出版的新书,拜托多多关注!
本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。
对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。
觉得本文有帮助?欢迎点赞并分享给更多的人。
阅读更多更新文章,请关注微信公众号【面向对象思考】