Is it a bad practice to use break in a for loop? [

2019-01-01 06:45发布

Is it a bad practice to use break statement inside a for loop?

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.

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?

I am asking in the context of a normal C or C++ for loop.

P.S: The MISRA coding guidelines advise against using break.

19条回答
情到深处是孤独
2楼-- · 2019-01-01 07:16

I don't see any reason why it would be a bad practice PROVIDED that you want to complete STOP processing at that point.

查看更多
十年一品温如言
3楼-- · 2019-01-01 07:20

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.

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.

查看更多
人间绝色
4楼-- · 2019-01-01 07:20

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.

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.')
查看更多
泪湿衣
5楼-- · 2019-01-01 07:20

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.

I think it makes more sense to have your checks at the top of your for loop like so

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 ;)

查看更多
与君花间醉酒
6楼-- · 2019-01-01 07:22

No, break is the correct solution.

Adding a boolean variable makes the code harder to read and adds a potential source of errors.

查看更多
骚的不知所云
7楼-- · 2019-01-01 07:23

I did some analysis on the codebase I'm currently working on (40,000 lines of JavaScript).

I found only 22 break statements, of those:

  • 19 were used inside switch statements (we only have 3 switch statements in total!).
  • 2 were used inside for loops - a code that I immediately classified as to be refactored into separate functions and replaced with return statement.
  • As for the final break inside while loop... I ran git blame to see who wrote this crap!

So according to my statistics: If break is used outside of switch, it is a code smell.

I also searched for continue statements. Found none.

查看更多
登录 后发表回答