前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.77:循环中尽量少用break和continue

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

作者头像
面向对象思考
发布2020-06-09 14:58:24
3680
发布2020-06-09 14:58:24
举报

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<T> 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<T> &vec)
{
    for (const T &item : vec) {
        if (/* some condition*/) return item;
    }
    return T(); //default value
}

void use2()
{
    std::vector<T> 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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-06-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ES.77: Minimize the use of break and continue in loops
  • Reason(原因)
    • Alternative(可选项)
      • Note(注意)
        • Enforcement(实施建议)
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档