C++ 使用被认为有害的“break”打破“for”循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3217425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:21:22  来源:igfitidea点击:

Breaking a "for" loop using "break" considered harmful?

c++loopsfor-loopgotobreak

提问by José Tomás Tocino

Some days ago I started a quick open source project and, when some mates looked at the code on svn, one of them told me that using breakstatement inside a forloop is considered harmful and shouldn't be done.

几天前我开始了一个快速的开源项目,当一些伙伴查看 svn 上的代码时,其中一个告诉我循环break内的using语句for被认为是有害的,不应该这样做。

He added, though, that I would find several cases of breakstatements inside forloops on Linux kernel source code, but that was just because only Linus Torvalds and Chuck Norris were allowed to use it and no one else.

不过,他补充说,我会在 Linux 内核源代码的循环break内找到几个语句案例for,但这只是因为只有 Linus Torvalds 和 Chuck Norris 被允许使用它,其他人都不允许使用它。

What do you think? I see no problem in using breakinside a forloop. In my opinion, emulating the behaviour of breakusing boolean variables or something alike adds a lot of innecesary overhead and makes the code less straightforward.

你怎么认为?我认为在循环break内使用没有问题for。在我看来,模拟break使用布尔变量或类似的行为会增加很多不必要的开销并使代码变得不那么简单。

Also, there's no room for comparison with goto, because breakcannot arbitrarily change program's flow from one point to the other lie gotodoes.

此外,没有与 比较的余地goto,因为break不能随意改变程序的流程从一个点到另一个点goto

回答by fire.eagle

I see no problem with using breaks. There will always be circumstances where you want to stop processing a loop, and using a break;makes much more sense (and makes it more readable!) than setting your loop counter up to a value that would make your loop stop at the next iteration.

我认为使用休息没有问题。在某些情况下,您总是希望停止处理循环,并且使用 abreak;比将循环计数器设置为一个可以使循环在下一次迭代中停止的值更有意义(并使其更具可读性!)。

回答by Matthew Flaschen

Obligatory:

强制性:

XKCD Goto

XKCD转到

The point is that you should not avoid it purely on grounds of bad practice (or velociraptors), but consider on a case by case basis.

关键是你不应该仅仅因为不好的做法(或速龙)而避免它,而是要根据具体情况考虑。

It's all about clarity. As you said, you never have to use it, but in some cases it promotes readability. It's useful when the loop usually terminates normally, but in rare cases you have to bail out. Loops that usually (or always) break are more of a code smell (but could still be appropriate).

这一切都与清晰度有关。正如您所说,您永远不必使用它,但在某些情况下,它会提高可读性。当循环通常正常终止时很有用,但在极少数情况下您必须退出。通常(或总是)中断的循环更像是一种代码气味(但仍然可能是合适的)。

回答by Thanatos

Not only is there no problem to using break, I'd say anyone saying it is "considered harmful" is downright wrong.

不仅使用没有问题break,我会说任何人说它“被认为有害”是完全错误的。

breakis a language feature used to abort a loop - you could use goto, but then you incur the (appropriate) wrath of the XKCD comic below. You could use a flag in the condition, but that hampers readability. breakis not only the easiest, but also the clearest way many times to bust out of a loop. Use it as it was meant to be used.

break是一种用于中止循环的语言功能 - 您可以使用goto,但随后您会招致下面 XKCD 漫画的(适当的)愤怒。您可以在条件中使用标志,但这会妨碍可读性。break不仅是最简单的,而且也是多次跳出循环的最清晰的方法。使用它,因为它应该被使用。



Edit:To get at a larger picture here: When you're writing code, the guiding principle to "should I use language feature X or Y" should be "which way will result in the more elegant code"? Elegance, in code, is pretty much an art, but I'd lay it down as a fine balance between readability and algorithmic (read: not micro-optimizations) efficiency. Readability is going to be determined by length, complexity of the code, etc. A one-line boost::bind may very well be harder to read & understand than a 3 line loop.

编辑:在这里获得更大的图景:在编写代码时,“我应该使用语言功能 X 还是 Y”的指导原则应该是“哪种方式会产生更优雅的代码”?优雅,在代码中,几乎是一门艺术,但我认为它是可读性和算法(阅读:不是微优化)效率之间的良好平衡。可读性将取决于代码的长度、复杂性等。单行 boost::bind 可能比 3 行循环更难阅读和理解。

If a language feature can help you write code that is easier to understand while getting the job done, then use it. This applies to break, goto, C++ exceptions, etc. Don't follow a "X is (evil|considered harmful)" blindly - apply common sense and logic each time.

如果语言功能可以帮助您编写在完成工作时更易于理解的代码,那么请使用它。这适用于breakgoto、 C++ 异常等。不要盲目地遵循“X 是(邪恶|被认为是有害的)”——每次都应用常识和逻辑。

回答by Cogwheel

Not only is there no problem with break, it's also OK to use gotowhen breakis insufficient. Don't be afraid of multiple returns, either.

不仅是有没有的问题break,它也OK使用gotobreak是不够的。也不要害怕多重回报。

All of the above only applies if it makes the code easier to understand*.

以上所有内容仅适用于使代码更易于理解的情况*。

*And if your PHBallows it...

*如果您的PHB允许...

回答by Scott Stafford

I think your mate is insane. breakis perfectly acceptable, perfectly readable, and perfectly maintainable. Period.

我觉得你男朋友疯了 break完全可以接受,完全可读,并且完全可维护。时期。

回答by txwikinger

There is a paradigm that any loop should only have one point of exit (same as a function should only have one return). This has to do with readability. Too many exit points can make the code very difficult to understand. Also, it is important if you want to do code verification (i.e. mathematically proof if your code is correct).

有一个范例,任何循环都应该只有一个退出点(与函数应该只有一个返回点一样)。这与可读性有关。太多的退出点会使代码很难理解。此外,如果您想进行代码验证(即如果您的代码正确,则进行数学证明)也很重要。

However, guidelines are often there to help, but are not strict. There are possibly situations where a break is better than not using it. Hence, one should be pragmatic about this, but understand the reason for such principles in order to create good code.

然而,指导方针通常可以提供帮助,但并不严格。在某些情况下,休息比不使用要好。因此,对此应该务实,但要了解这些原则的原因才能创建好的代码。

回答by Larry Wang

Incrementing your loop counter instead of using break also means you finish executing the current iteration of the loop, which may or may not be desirable.
Of course, you could wrap the rest of it in an ifclause, and then do it again when you realize you need to check whether or not to stop looping multiple times, and you will quickly realize why people use break;

增加循环计数器而不是使用 break 也意味着您完成了循环的当前迭代,这可能是也可能不是可取的。
当然,你可以把它的其余部分包装在一个if子句中,然后当你意识到你需要检查是否多次停止循环时再做一次,你很快就会意识到人们为什么使用break;

回答by Brian S

I think it depends on context. While it may be 'bad' coding style in some situations, I can't think of a case where it would be harmful.

我认为这取决于上下文。虽然在某些情况下它可能是“糟糕”的编码风格,但我想不出它会有害的情况

In fact, in some cases I would recommend it. For example, if you were using a linear search, any case (except the very worst case), a breakwould improve your speed.I think breaking out of the loop when you've found your needle would be perfectly acceptable, and it would be more readable than messing around with the loop variable (which might not solely be used for the loop, depending on your program) or wrapping the loop body in an ifblock. (And the other option, an ifwhich contains continue, combines the worst of two worlds: wrapping loop logic in an ifblock, and the poor coding style railed against by people like your friends who don't like break.)

事实上,在某些情况下,我会推荐它。例如,如果您使用的是线性搜索,任何情况下(除了最坏的情况),abreak都会提高您的速度。我认为当你发现你的针头时跳出循环是完全可以接受的,它比乱用循环变量(它可能不仅仅用于循环,取决于你的程序)或包装更具可读性if块中的循环体。(另一个选项,if其中包含continue,结合了两个世界中最糟糕的一个:将循环逻辑包装在一个if块中,以及像你的朋友这样不喜欢 的人所反对的糟糕的编码风格break。)

回答by Artelius

I suggest this algorithm if you're considering using a given technique.

如果您正在考虑使用给定的技术,我建议使用此算法。

  • If it is considered good practice:
    • use it.
  • If it is notconsidered good practice:
    • use it only if you judge it to be the best long-term solution.
  • If it is considered evil:
    • use it only if you judge it to be the best long-term solution and you are extremely confident in your judgement. Beware: things which are considered evil tend to be deceptively appealing.
  • 如果它被认为是好的做法
    • 用它。
  • 如果它被认为是好的做法:
    • 仅当您认为它是最好的长期解决方案时才使用它。
  • 如果它被认为是邪恶的
    • 只有当您认为它是最好的长期解决方案并且您对自己的判断非常有信心时才使用它。当心:被认为是邪恶的事物往往具有欺骗性的吸引力。

I would classify break;as "not good practice". Use it when it makes the code more readable, reduces the chance of bugs, does not complicate debugging, etc.

我会归类break;为“不好的做法”。当它使代码更具可读性,减少错误的机会,不使调试复杂化等时使用它。