在 c++ 中使用 goto 的正当理由
是否有任何合法理由使用 goto
在 C++ 程序中?我认识的每个人都说 goto 的定义是你编程错误,我同意这一点,因为我找不到任何使用 goto 的理由
Possible Duplicates:
GOTO considered harmless
GOTO still considered harmful?
Is there any legitimate reason to ever use goto
in a c++ program? Everyone i know says that the definition of goto is that youre programming something wrong, which i agree with, since i cant find any reason to use goto
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
goto
是一种优雅且高效的处理方法:另一个例子。假设你有一个巨大的函数 - 2K 行。不要感到惊讶,很多网络代码都有这个。在函数中,您会在不同的时间检测到需要相同错误处理的条件:
goto
在这一点上大放异彩。编辑下面的链接包含反驳 Dijkstra 文章的原始文章的部分内容。
“
GOTO
语句被视为有害”被视为有害goto
is one elegant + efficient way to handle this:Another example. Say you have a giant function - 2K lines. Don't be surprised, lots of networking code has this. And in the function, at various times, you detect conditions that require the same error handling:
goto
shines at this.EDIT the link below has portions of the original article countering Dijkstra's article.
"
GOTO
statement considered harmful" considered harmful当您需要打破深度嵌套循环时。假设您正在 3 维矩阵中搜索一个值:
当然,您始终可以定义一个函数并从中返回,但您可能会遇到编写函数的一次性用例(因此将代码移出上下文,携带所有变量,等等)仅仅为了避免使用
goto
是不值得的。When you need to break out of a deeply nested loop. Suppose you're searching for a value in a 3-dimensional matrix:
Of course you could always define a function and
return
out of it, but you may have one-time use cases in which writing a function (and thus moving the code out of context, carrying all the variables, and so on) is not worth the trouble just to avoid usinggoto
.您可以使用
goto
进行清理,例如:可能,可以通过在 C++ 中使用 RAII 以更好的方式实现,但来自 C 背景,这通常是
goto
所在的位置因此,如果出于任何原因你不能使用 RAII(我认为很难找到这样的场景 - 可能你根本没有使用任何智能指针等)那么它可能是一个合法的情况。You could use
goto
for cleanups, something like:Possibly, could be implemented in a better way by using RAII in C++ but coming from a C background this is often where
goto
is used, So if for any reason you cannot use RAII(I think hard to find such a scenario-possibly you are not using any smart pointers at all etc) then it can be a legitimate case.