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:33

Using break as well as continue in a for loop is perfectly fine.

It simplifies the code and improves its readability.

查看更多
还给你的自由
3楼-- · 2019-01-01 07:34

It's perfectly valid to use break - as others have pointed out, it's nowhere in the same league as 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.

查看更多
长期被迫恋爱
4楼-- · 2019-01-01 07:35

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.

查看更多
与风俱净
5楼-- · 2019-01-01 07:37

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.

查看更多
ら面具成の殇う
6楼-- · 2019-01-01 07:40

On MISRA 98 rules, that is used on my company in C dev, break statement shall not be used...

Edit : Break is allowed in MISRA '04

查看更多
梦醉为红颜
7楼-- · 2019-01-01 07:42

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.

查看更多
登录 后发表回答