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

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

问题描述

中为使用 break 语句 >循环



说,我正在一个数组中寻找一个值。在for循环中进行比较,当找到值的时候, break; 退出for循环。

不好的做法?我已经看到了使用的替代方法:定义一个变量 vFound ,并在找到该值时将其设置为true,并检查 vFound 中为语句条件。但是为了这个目的,是否需要创建一个新变量?



我正在问一个正常的C或C ++ for循环的上下文。
$ b

PS: MISRA编码准则建议不要使用中断。 / b>

解决方案

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

在for循环中使用 break continue 关联的大部分危险都会被否定写整洁,易读的循环。如果你的循环的主体跨越了几个屏幕的长度,并有多个嵌套的子块,是的,你可以很容易忘记一些代码将不会执行休息后。如果这个循环是短暂的,那么break语句的目的应该是显而易见的。



如果循环变得太大,使用一个或多个相反,在循环内有名的函数调用。避免这样做的唯一真正原因是为了处理瓶颈。


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.

解决方案

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.

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

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