千家信息网

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

发表于:2025-02-04 作者:千家信息网编辑
千家信息网最后更新 2025年02月04日,这篇文章主要介绍"C++中为什么循环中尽量少用break和continue",在日常操作中,相信很多人在C++中为什么循环中尽量少用break和continue问题上存在疑惑,小编查阅了各式资料,整理
千家信息网最后更新 2025年02月04日C++中为什么循环中尽量少用break和continue

这篇文章主要介绍"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 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语句。

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

0