C++核心准则ES.77:循环中尽量少用break和continue

共 1759字,需浏览 4分钟

 ·

2020-06-04 23:21

976f28c2763a40b8b26ef12c6c62f193.webp

ES.77: Minimize the use of break and continue in loops

ES.77:循环中尽量少用break和continue


Reason(原因)

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




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

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

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

浏览 31
点赞
评论
收藏
分享

手机扫一扫分享

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

手机扫一扫分享

分享
举报