Is it a bad practice to use break
statement inside a for
loop?
在for循环中使用break语句是不好的做法吗?
Say, I am searching for an value in an array. Compare inside a for loop and when value is found, break;
to exit the for loop.
比如说,我在数组中搜索一个值。在for循环内进行比较,当找到值时,中断;退出for循环。
Is this a bad practice? I have seen the alternative used: define a variable vFound
and set it to true when the value is found and check vFound
in the for
statement condition. But is it necessary to create a new variable just for this purpose?
这种做法不好吗?我已经看到了使用的替代方法:定义一个变量vFound,并将其设置为true,当发现值并在for语句条件中检查vFound时。但是,是否有必要为此目的创建一个新变量?
I am asking in the context of a normal C or C++ for loop.
我是在一个普通的C或c++循环上下文中提出这个问题的。
P.S: The MISRA coding guidelines advise against using break.
P。S: MISRA编码指南建议不要使用break。
19 个解决方案
#1
94
Lots of answers here, but I haven't seen this mentioned yet:
这里有很多的答案,但是我还没有看到这个提到:
Most of the "dangers" associated with using break
or continue
in a for loop are negated if you write tidy, easily-readable loops. If the body of your loop spans several screen lengths and has multiple nested sub-blocks, yes, you could easily forget that some code won't be executed after the break. If, however, the loop is short and to the point, the purpose of the break statement should be obvious.
如果您编写整洁、易读的循环,那么使用break或在for循环中继续的大多数“危险”都将被否定。如果循环的主体跨越了几个屏幕长度,并且有多个嵌套子块,那么您很容易忘记在中断之后不会执行某些代码。但是,如果循环是短的,并且到这个点,break语句的目的应该是显而易见的。
If a loop is getting too big, use one or more well-named function calls within the loop instead. The only real reason to avoid doing so is for processing bottlenecks.
如果一个循环太大,可以在循环中使用一个或多个命名良好的函数调用。避免这样做的唯一真正原因是处理瓶颈。
#2
121
No, break is the correct solution.
不,休息是正确的解决方法。
Adding a boolean variable makes the code harder to read and adds a potential source of errors.
添加布尔变量使代码更难读,并增加了潜在的错误源。
#3
47
You can find all sorts of professional code with 'break' statements in them. It perfectly make sense to use this whenever necessary. In your case this option is better than creating a separate variable just for the purpose of coming out of the loop.
您可以在其中找到各种带有“break”语句的专业代码。在必要的时候使用它是完全合理的。在您的例子中,这个选项比仅仅为了走出循环而创建一个单独的变量要好。
#4
42
Using break
as well as continue
in a for
loop is perfectly fine.
在for循环中使用break和continue是完全没问题的。
It simplifies the code and improves its readability.
它简化了代码并提高了可读性。
#5
18
Far from bad practice, Python (and other languages?) extended the for
loop structure so part of it will only be executed if the loop doesn't break
.
Python(和其他语言?)扩展了for循环结构,因此只有在循环没有中断的情况下才会执行它的一部分。
for n in range(5):
for m in range(3):
if m >= n:
print('stop!')
break
print(m, end=' ')
else:
print('finished.')
Output:
输出:
stop!
0 stop!
0 1 stop!
0 1 2 finished.
0 1 2 finished.
Equivalent code without break
and that handy else
:
等价的代码没有中断和方便的其他:
for n in range(5):
aborted = False
for m in range(3):
if not aborted:
if m >= n:
print('stop!')
aborted = True
else:
print(m, end=' ')
if not aborted:
print('finished.')
#6
14
General rule: If following a rule requires you to do something more awkward and difficult to read then breaking the rule, then break the rule.
一般规则:如果遵循一个规则需要你做一些更尴尬和更困难的事情,然后打破规则,然后打破规则。
In the case of looping until you find something, you run into the problem of distinguishing found versus not found when you get out. That is:
在循环直到找到某样东西的情况下,您会遇到区分已找到与未找到的问题。那就是:
for (int x=0;x<fooCount;++x)
{
Foo foo=getFooSomehow(x);
if (foo.bar==42)
break;
}
// So when we get here, did we find one, or did we fall out the bottom?
So okay, you can set a flag, or initialize a "found" value to null. But
你可以设置一个标志,或者初始化一个" find "值为null。但
That's why in general I prefer to push my searches into functions:
这就是为什么我一般更喜欢把我的搜索推进功能:
Foo findFoo(int wantBar)
{
for (int x=0;x<fooCount;++x)
{
Foo foo=getFooSomehow(x);
if (foo.bar==wantBar)
return foo;
}
// Not found
return null;
}
This also helps to unclutter the code. In the main line, "find" becomes a single statement, and when the conditions are complex, they're only written once.
这也有助于消除代码的混乱。在主线中,“查找”变成了一个单独的语句,当条件很复杂时,它们只写一次。
#7
13
It depends on the language. While you can possibly check a boolean variable here:
这取决于语言。你可以在这里检查布尔变量:
for (int i = 0; i < 100 && stayInLoop; i++) { ... }
it is not possible to do it when itering over an array:
当它在一个数组上时,是不可能做到的:
for element in bigList: ...
Anyway, break
would make both codes more readable.
无论如何,break将使这两个代码更具可读性。
#8
12
There is nothing inherently wrong with using a break statement but nested loops can get confusing. To improve readability many languages (at least Java does) support breaking to labels which will greatly improve readability.
使用break语句本身没有什么错,但是嵌套循环可能会让人感到困惑。为了提高可读性,许多语言(至少是Java)都支持对标签的破坏,这将极大地提高可读性。
int[] iArray = new int[]{0,1,2,3,4,5,6,7,8,9};
int[] jArray = new int[]{0,1,2,3,4,5,6,7,8,9};
// label for i loop
iLoop: for (int i = 0; i < iArray.length; i++) {
// label for j loop
jLoop: for (int j = 0; j < jArray.length; j++) {
if(iArray[i] < jArray[j]){
// break i and j loops
break iLoop;
} else if (iArray[i] > jArray[j]){
// breaks only j loop
break jLoop;
} else {
// unclear which loop is ending
// (breaks only the j loop)
break;
}
}
}
I will say that break (and return) statements often increase cyclomatic complexity which makes it harder to prove code is doing the correct thing in all cases.
我要说的是,break(和return)语句经常增加圈复杂度,这使得证明代码在所有情况下都是正确的变得更加困难。
If you're considering using a break while iterating over a sequence for some particular item, you might want to reconsider the data structure used to hold your data. Using something like a Set or Map may provide better results.
如果在迭代某个特定项的序列时考虑使用break,那么您可能需要重新考虑用于保存数据的数据结构。使用集合或地图之类的东西可能会提供更好的结果。
#9
11
break is a completely acceptable statement to use (so is continue, btw). It's all about code readability -- as long as you don't have overcomplicated loops and such, it's fine.
break是一个完全可以接受的语句(顺便说一句,继续也是如此)。所有这些都是关于代码可读性的——只要您没有复杂的循环之类的,就可以了。
It's not like they were the same league as goto. :)
他们和哥托不一样。:)
#10
7
In your example you do not know the number of iterations for the for loop. Why not use while loop instead, which allows the number of iterations to be indeterminate at the beginning?
在您的示例中,您不知道for循环的迭代次数。为什么不使用while循环,它允许迭代的数量在开始时是不确定的呢?
It is hence not necessary to use break statemement in general, as the loop can be better stated as a while loop.
因此一般不需要使用break statemement,因为循环可以更好地表示为while循环。
#11
7
I agree with others who recommend using break
. The obvious consequential question is why would anyone recommend otherwise? Well... when you use break, you skip the rest of the code in the block, and the remaining iterations. Sometimes this causes bugs, for example:
我同意其他人建议使用break。显而易见的重要问题是,为什么有人会提出不同的建议呢?嗯…当您使用break时,您将跳过块中的其余代码,以及其余的迭代。有时这会导致bug,例如:
-
a resource acquired at the top of the block may be released at the bottom (this is true even for blocks inside
for
loops), but that release step may be accidentally skipped when a "premature" exit is caused by abreak
statement (in "modern" C++, "RAII" is used to handle this in a reliable and exception-safe way: basically, object destructors free resources reliably no matter how a scope is exited)资源获取的顶部块可能释放底部(这是真的,甚至对于块内循环),但这可能是不小心跳过发布步骤引起的“过早”退出时break语句(在“现代”c++,“RAII”是用于处理这个异常安全可靠的方式:基本上,对象析构函数免费资源可靠无论如何退出范围)
-
someone may change the conditional test in the
for
statement without noticing that there are other delocalised exit conditions有些人可能会在for语句中更改条件测试,而不会注意到还有其他非域化的退出条件
-
ndim's answer observes that some people may avoid
break
s to maintain a relatively consistent loop run-time, but you were comparingbreak
against use of a boolean early-exit control variable where that doesn't holdndim的回答指出,有些人可能会避免中断来维护一个相对一致的循环运行时,但是您将中断与使用布尔早期退出控制变量进行比较
Every now and then people observing such bugs realise they can be prevented/mitigated by this "no breaks" rule... indeed, there's a whole related strategy for "safer" programming called "structured programming", where each function is supposed to have a single entry and exit point too (i.e. no goto, no early return). It may eliminate some bugs, but it doubtless introduces others. Why do they do it?
每隔一段时间,观察这些虫子的人就会意识到,这种“不间断”的规则可以防止或减轻这种错误。实际上,有一种“更安全”的编程策略叫做“结构化编程”,每个函数都应该有一个入口点和出口点(也就是说,不去任何地方,不早返回)。它可能会消除一些bug,但无疑会引入其他bug。他们为什么要这么做?
- they have a development framework that encourages a particular style of programming / code, and they've statistical evidence that this produces a net benefit in that limited framework, or
- 他们有一个开发框架,鼓励一种特定风格的编程/代码,并且他们有统计证据表明这在那个有限的框架中产生了净效益
- they've been influenced by programming guidelines or experience within such a framework, or
- 在这样的框架中,他们受到编程指南或经验的影响
- they're just dictatorial idiots, or
- 他们只是专横的白痴
- any of the above + historical inertia (relevant in that the justifications are more applicable to C than modern C++).
- 上述任何+历史惯量(相关的理由比现代c++更适用于C)。
#12
4
It's perfectly valid to use break
- as others have pointed out, it's nowhere in the same league as goto
.
使用break是完全合理的——正如其他人指出的那样,它与goto完全不同。
Although you might want to use the vFound
variable when you want to check outside the loop whether the value was found in the array. Also from a maintainability point of view, having a common flag signalling the exit criteria might be useful.
虽然您可能希望在检查循环外部时使用vFound变量,但是否在数组中找到值。同样,从可维护性的角度来看,使用一个公共标志来标志退出标准可能是有用的。
#13
4
I don't see any reason why it would be a bad practice PROVIDED that you want to complete STOP processing at that point.
如果您想在那个时候完成停止处理,我不认为这是一个糟糕的实践。
#14
4
In the embedded world, there is a lot of code out there that uses the following construct:
在嵌入式世界中,有很多代码使用以下结构:
while(1)
{
if (RCIF)
gx();
if (command_received == command_we_are_waiting_on)
break;
else if ((num_attempts > MAX_ATTEMPTS) || (TickGet() - BaseTick > MAX_TIMEOUT))
return ERROR;
num_attempts++;
}
if (call_some_bool_returning_function())
return TRUE;
else
return FALSE;
This is a very generic example, lots of things are happening behind the curtain, interrupts in particular. Don't use this as boilerplate code, I'm just trying to illustrate an example.
这是一个很普通的例子,很多事情都发生在幕后,特别是中断。不要把它用作样板代码,我只是想举例说明。
My personal opinion is that there is nothing wrong with writing a loop in this manner as long as appropriate care is taken to prevent remaining in the loop indefinitely.
我个人的观点是,以这种方式编写循环没有错,只要采取适当的注意,以防止无限期地留在循环中。
#15
3
Depends on your use case. There are applications where the runtime of a for loop needs to be constant (e.g. to satisfy some timing constraints, or to hide your data internals from timing based attacks).
取决于您的用例。在某些应用程序中,for循环的运行时需要是常量(例如,为了满足某些时间限制,或者为了隐藏数据内部以避免基于时间的攻击)。
In those cases it will even make sense to set a flag and only check the flag value AFTER all the for
loop iterations have actually run. Of course, all the for loop iterations need to run code that still takes about the same time.
在这些情况下,甚至可以设置一个标志,并在所有for循环迭代实际运行之后检查标志值。当然,所有的for循环迭代都需要运行同样时间的代码。
If you do not care about the run time... use break;
and continue;
to make the code easier to read.
如果你不关心运行时间……使用打破;并继续;使代码更容易阅读。
#16
3
I did some analysis on the codebase I'm currently working on (40,000 lines of JavaScript).
我对我正在开发的代码基做了一些分析(40000行JavaScript)。
I found only 22 break
statements, of those:
我只找到了22个中断语句,其中:
- 19 were used inside
switch
statements (we only have 3 switch statements in total!). - 在switch语句中使用了19个(总共只有3个switch语句!)
- 2 were used inside
for
loops - a code that I immediately classified as to be refactored into separate functions and replaced withreturn
statement. - 在循环内部使用了2—我立即将其分类为将被重构为独立函数并替换为return语句的代码。
- As for the final
break
insidewhile
loop... I rangit blame
to see who wrote this crap! - 至于内循环的最后突破……我跑去责怪谁写了这些废话!
So according to my statistics: If break
is used outside of switch
, it is a code smell.
所以根据我的统计:如果break是在switch之外使用的,那么它就是一种代码味道。
I also searched for continue
statements. Found none.
我还搜索了continue语句。发现没有。
#17
2
On MISRA 98 rules, that is used on my company in C dev, break statement shall not be used...
关于MISRA 98规则,我公司在C开发中使用,break语句不能用……
Edit : Break is allowed in MISRA '04
编辑:在MISRA '04中可以休息
#18
1
I disagree!
我不同意!
Why would you ignore the built-in functionality of a for loop to make your own? You do not need to reinvent the wheel.
为什么要忽略for循环的内置功能来创建自己的循环呢?你不需要重新发明*。
I think it makes more sense to have your checks at the top of your for loop like so
我认为把支票放在for循环的顶部更有意义
for(int i = 0; i < myCollection.Length && myCollection[i].SomeValue != "Break Condition"; i++)
{
//loop body
}
or if you need to process the row first
或者如果需要先处理行
for(int i = 0; i < myCollection.Length && (i == 0 ? true : myCollection[i-1].SomeValue != "Break Condition"); i++)
{
//loop body
}
This way you can write a function to perform everything and make much cleaner code.
通过这种方式,您可以编写一个函数来执行所有操作,并生成更清晰的代码。
for(int i = 0; i < myCollection.Length && (i == 0 ? true : myCollection[i-1].SomeValue != "Break Condition"); i++)
{
DoAllThatCrazyStuff(myCollection[i]);
}
Or if your condition is complicated you can move that code out too!
或者如果你的情况很复杂,你也可以把代码移出来!
for(int i = 0; i < myCollection.Length && BreakFunctionCheck(i, myCollection); i++)
{
DoAllThatCrazyStuff(myCollection[i]);
}
"Professional Code" that is riddled with breaks doesn't really sound like professional code to me. It sounds like lazy coding ;)
对我来说,充满漏洞的“专业代码”听起来并不像专业代码。这听起来像是懒惰的编码;)
#19
0
Ofcourse, break;
is the solution to stop the for loop or foreach loop. I used it in php in foreach and for loop and found working.
当然,休息;是阻止for循环或foreach循环的解决方案。我在foreach和for循环中使用它,并找到了工作。
#1
94
Lots of answers here, but I haven't seen this mentioned yet:
这里有很多的答案,但是我还没有看到这个提到:
Most of the "dangers" associated with using break
or continue
in a for loop are negated if you write tidy, easily-readable loops. If the body of your loop spans several screen lengths and has multiple nested sub-blocks, yes, you could easily forget that some code won't be executed after the break. If, however, the loop is short and to the point, the purpose of the break statement should be obvious.
如果您编写整洁、易读的循环,那么使用break或在for循环中继续的大多数“危险”都将被否定。如果循环的主体跨越了几个屏幕长度,并且有多个嵌套子块,那么您很容易忘记在中断之后不会执行某些代码。但是,如果循环是短的,并且到这个点,break语句的目的应该是显而易见的。
If a loop is getting too big, use one or more well-named function calls within the loop instead. The only real reason to avoid doing so is for processing bottlenecks.
如果一个循环太大,可以在循环中使用一个或多个命名良好的函数调用。避免这样做的唯一真正原因是处理瓶颈。
#2
121
No, break is the correct solution.
不,休息是正确的解决方法。
Adding a boolean variable makes the code harder to read and adds a potential source of errors.
添加布尔变量使代码更难读,并增加了潜在的错误源。
#3
47
You can find all sorts of professional code with 'break' statements in them. It perfectly make sense to use this whenever necessary. In your case this option is better than creating a separate variable just for the purpose of coming out of the loop.
您可以在其中找到各种带有“break”语句的专业代码。在必要的时候使用它是完全合理的。在您的例子中,这个选项比仅仅为了走出循环而创建一个单独的变量要好。
#4
42
Using break
as well as continue
in a for
loop is perfectly fine.
在for循环中使用break和continue是完全没问题的。
It simplifies the code and improves its readability.
它简化了代码并提高了可读性。
#5
18
Far from bad practice, Python (and other languages?) extended the for
loop structure so part of it will only be executed if the loop doesn't break
.
Python(和其他语言?)扩展了for循环结构,因此只有在循环没有中断的情况下才会执行它的一部分。
for n in range(5):
for m in range(3):
if m >= n:
print('stop!')
break
print(m, end=' ')
else:
print('finished.')
Output:
输出:
stop!
0 stop!
0 1 stop!
0 1 2 finished.
0 1 2 finished.
Equivalent code without break
and that handy else
:
等价的代码没有中断和方便的其他:
for n in range(5):
aborted = False
for m in range(3):
if not aborted:
if m >= n:
print('stop!')
aborted = True
else:
print(m, end=' ')
if not aborted:
print('finished.')
#6
14
General rule: If following a rule requires you to do something more awkward and difficult to read then breaking the rule, then break the rule.
一般规则:如果遵循一个规则需要你做一些更尴尬和更困难的事情,然后打破规则,然后打破规则。
In the case of looping until you find something, you run into the problem of distinguishing found versus not found when you get out. That is:
在循环直到找到某样东西的情况下,您会遇到区分已找到与未找到的问题。那就是:
for (int x=0;x<fooCount;++x)
{
Foo foo=getFooSomehow(x);
if (foo.bar==42)
break;
}
// So when we get here, did we find one, or did we fall out the bottom?
So okay, you can set a flag, or initialize a "found" value to null. But
你可以设置一个标志,或者初始化一个" find "值为null。但
That's why in general I prefer to push my searches into functions:
这就是为什么我一般更喜欢把我的搜索推进功能:
Foo findFoo(int wantBar)
{
for (int x=0;x<fooCount;++x)
{
Foo foo=getFooSomehow(x);
if (foo.bar==wantBar)
return foo;
}
// Not found
return null;
}
This also helps to unclutter the code. In the main line, "find" becomes a single statement, and when the conditions are complex, they're only written once.
这也有助于消除代码的混乱。在主线中,“查找”变成了一个单独的语句,当条件很复杂时,它们只写一次。
#7
13
It depends on the language. While you can possibly check a boolean variable here:
这取决于语言。你可以在这里检查布尔变量:
for (int i = 0; i < 100 && stayInLoop; i++) { ... }
it is not possible to do it when itering over an array:
当它在一个数组上时,是不可能做到的:
for element in bigList: ...
Anyway, break
would make both codes more readable.
无论如何,break将使这两个代码更具可读性。
#8
12
There is nothing inherently wrong with using a break statement but nested loops can get confusing. To improve readability many languages (at least Java does) support breaking to labels which will greatly improve readability.
使用break语句本身没有什么错,但是嵌套循环可能会让人感到困惑。为了提高可读性,许多语言(至少是Java)都支持对标签的破坏,这将极大地提高可读性。
int[] iArray = new int[]{0,1,2,3,4,5,6,7,8,9};
int[] jArray = new int[]{0,1,2,3,4,5,6,7,8,9};
// label for i loop
iLoop: for (int i = 0; i < iArray.length; i++) {
// label for j loop
jLoop: for (int j = 0; j < jArray.length; j++) {
if(iArray[i] < jArray[j]){
// break i and j loops
break iLoop;
} else if (iArray[i] > jArray[j]){
// breaks only j loop
break jLoop;
} else {
// unclear which loop is ending
// (breaks only the j loop)
break;
}
}
}
I will say that break (and return) statements often increase cyclomatic complexity which makes it harder to prove code is doing the correct thing in all cases.
我要说的是,break(和return)语句经常增加圈复杂度,这使得证明代码在所有情况下都是正确的变得更加困难。
If you're considering using a break while iterating over a sequence for some particular item, you might want to reconsider the data structure used to hold your data. Using something like a Set or Map may provide better results.
如果在迭代某个特定项的序列时考虑使用break,那么您可能需要重新考虑用于保存数据的数据结构。使用集合或地图之类的东西可能会提供更好的结果。
#9
11
break is a completely acceptable statement to use (so is continue, btw). It's all about code readability -- as long as you don't have overcomplicated loops and such, it's fine.
break是一个完全可以接受的语句(顺便说一句,继续也是如此)。所有这些都是关于代码可读性的——只要您没有复杂的循环之类的,就可以了。
It's not like they were the same league as goto. :)
他们和哥托不一样。:)
#10
7
In your example you do not know the number of iterations for the for loop. Why not use while loop instead, which allows the number of iterations to be indeterminate at the beginning?
在您的示例中,您不知道for循环的迭代次数。为什么不使用while循环,它允许迭代的数量在开始时是不确定的呢?
It is hence not necessary to use break statemement in general, as the loop can be better stated as a while loop.
因此一般不需要使用break statemement,因为循环可以更好地表示为while循环。
#11
7
I agree with others who recommend using break
. The obvious consequential question is why would anyone recommend otherwise? Well... when you use break, you skip the rest of the code in the block, and the remaining iterations. Sometimes this causes bugs, for example:
我同意其他人建议使用break。显而易见的重要问题是,为什么有人会提出不同的建议呢?嗯…当您使用break时,您将跳过块中的其余代码,以及其余的迭代。有时这会导致bug,例如:
-
a resource acquired at the top of the block may be released at the bottom (this is true even for blocks inside
for
loops), but that release step may be accidentally skipped when a "premature" exit is caused by abreak
statement (in "modern" C++, "RAII" is used to handle this in a reliable and exception-safe way: basically, object destructors free resources reliably no matter how a scope is exited)资源获取的顶部块可能释放底部(这是真的,甚至对于块内循环),但这可能是不小心跳过发布步骤引起的“过早”退出时break语句(在“现代”c++,“RAII”是用于处理这个异常安全可靠的方式:基本上,对象析构函数免费资源可靠无论如何退出范围)
-
someone may change the conditional test in the
for
statement without noticing that there are other delocalised exit conditions有些人可能会在for语句中更改条件测试,而不会注意到还有其他非域化的退出条件
-
ndim's answer observes that some people may avoid
break
s to maintain a relatively consistent loop run-time, but you were comparingbreak
against use of a boolean early-exit control variable where that doesn't holdndim的回答指出,有些人可能会避免中断来维护一个相对一致的循环运行时,但是您将中断与使用布尔早期退出控制变量进行比较
Every now and then people observing such bugs realise they can be prevented/mitigated by this "no breaks" rule... indeed, there's a whole related strategy for "safer" programming called "structured programming", where each function is supposed to have a single entry and exit point too (i.e. no goto, no early return). It may eliminate some bugs, but it doubtless introduces others. Why do they do it?
每隔一段时间,观察这些虫子的人就会意识到,这种“不间断”的规则可以防止或减轻这种错误。实际上,有一种“更安全”的编程策略叫做“结构化编程”,每个函数都应该有一个入口点和出口点(也就是说,不去任何地方,不早返回)。它可能会消除一些bug,但无疑会引入其他bug。他们为什么要这么做?
- they have a development framework that encourages a particular style of programming / code, and they've statistical evidence that this produces a net benefit in that limited framework, or
- 他们有一个开发框架,鼓励一种特定风格的编程/代码,并且他们有统计证据表明这在那个有限的框架中产生了净效益
- they've been influenced by programming guidelines or experience within such a framework, or
- 在这样的框架中,他们受到编程指南或经验的影响
- they're just dictatorial idiots, or
- 他们只是专横的白痴
- any of the above + historical inertia (relevant in that the justifications are more applicable to C than modern C++).
- 上述任何+历史惯量(相关的理由比现代c++更适用于C)。
#12
4
It's perfectly valid to use break
- as others have pointed out, it's nowhere in the same league as goto
.
使用break是完全合理的——正如其他人指出的那样,它与goto完全不同。
Although you might want to use the vFound
variable when you want to check outside the loop whether the value was found in the array. Also from a maintainability point of view, having a common flag signalling the exit criteria might be useful.
虽然您可能希望在检查循环外部时使用vFound变量,但是否在数组中找到值。同样,从可维护性的角度来看,使用一个公共标志来标志退出标准可能是有用的。
#13
4
I don't see any reason why it would be a bad practice PROVIDED that you want to complete STOP processing at that point.
如果您想在那个时候完成停止处理,我不认为这是一个糟糕的实践。
#14
4
In the embedded world, there is a lot of code out there that uses the following construct:
在嵌入式世界中,有很多代码使用以下结构:
while(1)
{
if (RCIF)
gx();
if (command_received == command_we_are_waiting_on)
break;
else if ((num_attempts > MAX_ATTEMPTS) || (TickGet() - BaseTick > MAX_TIMEOUT))
return ERROR;
num_attempts++;
}
if (call_some_bool_returning_function())
return TRUE;
else
return FALSE;
This is a very generic example, lots of things are happening behind the curtain, interrupts in particular. Don't use this as boilerplate code, I'm just trying to illustrate an example.
这是一个很普通的例子,很多事情都发生在幕后,特别是中断。不要把它用作样板代码,我只是想举例说明。
My personal opinion is that there is nothing wrong with writing a loop in this manner as long as appropriate care is taken to prevent remaining in the loop indefinitely.
我个人的观点是,以这种方式编写循环没有错,只要采取适当的注意,以防止无限期地留在循环中。
#15
3
Depends on your use case. There are applications where the runtime of a for loop needs to be constant (e.g. to satisfy some timing constraints, or to hide your data internals from timing based attacks).
取决于您的用例。在某些应用程序中,for循环的运行时需要是常量(例如,为了满足某些时间限制,或者为了隐藏数据内部以避免基于时间的攻击)。
In those cases it will even make sense to set a flag and only check the flag value AFTER all the for
loop iterations have actually run. Of course, all the for loop iterations need to run code that still takes about the same time.
在这些情况下,甚至可以设置一个标志,并在所有for循环迭代实际运行之后检查标志值。当然,所有的for循环迭代都需要运行同样时间的代码。
If you do not care about the run time... use break;
and continue;
to make the code easier to read.
如果你不关心运行时间……使用打破;并继续;使代码更容易阅读。
#16
3
I did some analysis on the codebase I'm currently working on (40,000 lines of JavaScript).
我对我正在开发的代码基做了一些分析(40000行JavaScript)。
I found only 22 break
statements, of those:
我只找到了22个中断语句,其中:
- 19 were used inside
switch
statements (we only have 3 switch statements in total!). - 在switch语句中使用了19个(总共只有3个switch语句!)
- 2 were used inside
for
loops - a code that I immediately classified as to be refactored into separate functions and replaced withreturn
statement. - 在循环内部使用了2—我立即将其分类为将被重构为独立函数并替换为return语句的代码。
- As for the final
break
insidewhile
loop... I rangit blame
to see who wrote this crap! - 至于内循环的最后突破……我跑去责怪谁写了这些废话!
So according to my statistics: If break
is used outside of switch
, it is a code smell.
所以根据我的统计:如果break是在switch之外使用的,那么它就是一种代码味道。
I also searched for continue
statements. Found none.
我还搜索了continue语句。发现没有。
#17
2
On MISRA 98 rules, that is used on my company in C dev, break statement shall not be used...
关于MISRA 98规则,我公司在C开发中使用,break语句不能用……
Edit : Break is allowed in MISRA '04
编辑:在MISRA '04中可以休息
#18
1
I disagree!
我不同意!
Why would you ignore the built-in functionality of a for loop to make your own? You do not need to reinvent the wheel.
为什么要忽略for循环的内置功能来创建自己的循环呢?你不需要重新发明*。
I think it makes more sense to have your checks at the top of your for loop like so
我认为把支票放在for循环的顶部更有意义
for(int i = 0; i < myCollection.Length && myCollection[i].SomeValue != "Break Condition"; i++)
{
//loop body
}
or if you need to process the row first
或者如果需要先处理行
for(int i = 0; i < myCollection.Length && (i == 0 ? true : myCollection[i-1].SomeValue != "Break Condition"); i++)
{
//loop body
}
This way you can write a function to perform everything and make much cleaner code.
通过这种方式,您可以编写一个函数来执行所有操作,并生成更清晰的代码。
for(int i = 0; i < myCollection.Length && (i == 0 ? true : myCollection[i-1].SomeValue != "Break Condition"); i++)
{
DoAllThatCrazyStuff(myCollection[i]);
}
Or if your condition is complicated you can move that code out too!
或者如果你的情况很复杂,你也可以把代码移出来!
for(int i = 0; i < myCollection.Length && BreakFunctionCheck(i, myCollection); i++)
{
DoAllThatCrazyStuff(myCollection[i]);
}
"Professional Code" that is riddled with breaks doesn't really sound like professional code to me. It sounds like lazy coding ;)
对我来说,充满漏洞的“专业代码”听起来并不像专业代码。这听起来像是懒惰的编码;)
#19
0
Ofcourse, break;
is the solution to stop the for loop or foreach loop. I used it in php in foreach and for loop and found working.
当然,休息;是阻止for循环或foreach循环的解决方案。我在foreach和for循环中使用它,并找到了工作。