每个人都知道Dijkstra的《致编辑的信》:goto语句被认为是有害的(这里。html transcript和这里。pdf),从那时起,就有一种强大的推动力,尽可能避免使用goto语句。虽然可以使用goto来生成不可维护的、庞大的代码,但它仍然存在于现代编程语言中。即使Scheme中先进的连续控制结构也可以被描述为复杂的后向。

在什么情况下需要使用goto?什么时候最好避免?

作为一个后续问题:C提供了一对函数setjmp()和longjmp(),它们不仅提供了在当前堆栈帧内进行跳转的能力,还提供了在任何调用帧内进行跳转的能力。这些应该被认为和goto一样危险吗?更危险?


Dijkstra自己也对这个头衔感到后悔,因为这不是他的责任。在EWD1308的结尾(也在这里。pdf),他写道:

Finally a short story for the record. In 1968, the Communications of the ACM published a text of mine under the title "The goto statement considered harmful", which in later years would be most frequently referenced, regrettably, however, often by authors who had seen no more of it than its title, which became a cornerstone of my fame by becoming a template: we would see all sorts of articles under the title "X considered harmful" for almost any X, including one titled "Dijkstra considered harmful". But what had happened? I had submitted a paper under the title "A case against the goto statement", which, in order to speed up its publication, the editor had changed into a "letter to the Editor", and in the process he had given it a new title of his own invention! The editor was Niklaus Wirth.

Donald E. Knuth写了一篇关于这个主题的经典论文,它与Dijkstra的论文相匹配,那就是结构化编程与语句。阅读既有助于重建上下文,也有助于对主题的非教条性理解。在本文中,Dijkstra对这个案例的观点被报道,并且更加强烈:

Donald E. Knuth:我相信通过呈现这样一个 事实上,我并不是不同意 Dijkstra的观点,因为 他最近写道: “请不要落入。 相信我是可怕的 教条的关于[去]的教条的 声明)。我觉得很不舒服 感觉别人在做 宗教出来了,好像 编程的概念问题 只用一个小技巧就能解决,用什么 一种简单的编码纪律!”


当前回答

实际上,我发现自己不得不使用goto,因为我真的想不出更好(更快)的方法来编写这段代码:

我有一个复杂的对象,我需要对它做一些操作。如果对象处于一种状态,那么我就可以进行快速操作,否则我就必须进行慢速操作。问题是,在某些情况下,在缓慢的手术过程中,可能会意识到这可以用快速手术来完成。

SomeObject someObject;    

if (someObject.IsComplex())    // this test is trivial
{
    // begin slow calculations here
    if (result of calculations)
    {
        // just discovered that I could use the fast calculation !
        goto Fast_Calculations;
    }
    // do the rest of the slow calculations here
    return;
}

if (someObject.IsmediumComplex())    // this test is slightly less trivial
{
    Fast_Calculations:
    // Do fast calculations
    return;
}

// object is simple, no calculations needed.

这是一个实时UI代码的速度关键部分,所以我真的认为GOTO在这里是合理的。

Hugo

其他回答

我的一个同事说,使用GOTO的唯一原因是,如果你把自己逼到了绝境,这是唯一的出路。换句话说,提前进行适当的设计,以后就不需要使用GOTO了。

我认为这幅漫画很好地说明了“我可以重构程序的流程,或者用一个小的‘GOTO’来代替。”当你的设计不完善时,GOTO是一种不完善的方法。迅猛龙捕食弱者。

我只需要它在基本(即。VB, VBScript等)和批处理文件。然后我只将它用于错误处理。在Basic中,我倾向于只使用“on error goto”。在批处理文件中,我必须使用它,因为没有其他命令。然后,我只使用它们作为向前跳转到有意义的标签。

用于调度的计算gotos通常比非常大的switch语句更容易理解。

对于错误和联合线程,我认为setcontext或setjmp(如果可用)是“更好的”。

几乎所有可以使用goto的情况,都可以使用其他结构实现相同的效果。无论如何,编译器都会使用Goto。

我个人从来没有明确地使用它,也不需要。

goto有一些问题。一是很难看到代码是如何流动的。因为花括号,所以更容易看到if-block,但是goto隐藏了它。此外,while和if本质上也是goto,但它们有助于解释为什么要在代码中来回跳转。有了一个固定的目标,你必须自己拼凑起来。

作为练习,试着编写一些计算斐波那契数列的代码,看看当你完成后,它有多难阅读。

如果你要处理这些代码,那么我建议你写一些单元测试,然后重写它。否则,就顺其自然吧。

尽管如此,有时出于性能原因,使用goto“可能”是合适的。