在 for 循环中使用 break 是一种不好的做法吗? [英] Is it a bad practice to use break in a for loop?

查看:45
本文介绍了在 for 循环中使用 break 是一种不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for 循环中使用 break 语句 是不是不好的做法?

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

比如说,我在数组中搜索一个值.在 for 循环内部进行比较,当找到值时,break; 退出 for 循环.

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.

这是一种不好的做法吗?我已经看到使用的替代方法:定义一个变量 vFound 并在找到值时将其设置为 true 并检查 for 语句条件中的 vFound.但是是否有必要为此创建一个新变量?

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?

我是在普通 C 或 C++ for 循环的上下文中询问.

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

P.S:MISRA 编码指南建议不要使用 break.

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

推荐答案

这里有很多答案,但我还没有看到提到这个:

Lots of answers here, but I haven't seen this mentioned yet:

如果您编写整洁、易于阅读的循环,与在 for 循环中使用 breakcontinue 相关的大多数危险"都会被否定.如果你的循环体跨越几个屏幕长度并且有多个嵌套的子块,是的,你很容易忘记一些代码在中断后不会被执行.但是,如果循环很短且切中要害,那么 break 语句的目的就很明显了.

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.

这篇关于在 for 循环中使用 break 是一种不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆