温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++中为什么循环中尽量少用break和continue

发布时间:2021-11-26 13:36:52 来源:亿速云 阅读:291 作者:iii 栏目:大数据

这篇文章主要介绍“C++中为什么循环中尽量少用break和continue”,在日常操作中,相信很多人在C++中为什么循环中尽量少用break和continue问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C++中为什么循环中尽量少用break和continue”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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

Reason(原因)

在不规整的循环体中,很容易忽略掉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语句。

到此,关于“C++中为什么循环中尽量少用break和continue”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI