每个人都知道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的地方是当你需要处理错误时,每一个特定的错误点都需要特殊的处理。

例如,如果您正在获取资源并使用信号量或互斥,您必须按顺序获取它们,并且应该始终以相反的方式释放它们。

一些代码需要一种非常奇怪的模式来获取这些资源,并且您不能仅仅编写一个易于维护和理解的控制结构来正确处理这些资源的获取和释放以避免死锁。

在没有goto的情况下总是可以做得很好,但在这种情况下和其他一些情况下,goto实际上是更好的解决方案,主要是为了可读性和可维护性。

亚当

其他回答

有时候,在一个函数中使用GOTO作为异常处理的替代是有效的:

    if (f() == false) goto err_cleanup;
    if (g() == false) goto err_cleanup;
    if (h() == false) goto err_cleanup;
    
    return;
    
    err_cleanup:
    ...

COM代码似乎经常陷入这种模式。

以下陈述是概括;尽管抗辩例外总是可能的,但通常(以我的经验和拙见)不值得冒险。

Unconstrained use of memory addresses (either GOTO or raw pointers) provides too many opportunities to make easily avoidable mistakes. The more ways there are to arrive at a particular "location" in the code, the less confident one can be about what the state of the system is at that point. (See below.) Structured programming IMHO is less about "avoiding GOTOs" and more about making the structure of the code match the structure of the data. For example, a repeating data structure (e.g. array, sequential file, etc.) is naturally processed by a repeated unit of code. Having built-in structures (e.g. while, for, until, for-each, etc.) allows the programmer to avoid the tedium of repeating the same cliched code patterns. Even if GOTO is low-level implementation detail (not always the case!) it's below the level that the programmer should be thinking. How many programmers balance their personal checkbooks in raw binary? How many programmers worry about which sector on the disk contains a particular record, instead of just providing a key to a database engine (and how many ways could things go wrong if we really wrote all of our programs in terms of physical disk sectors)?

以上附注:

关于第2点,考虑以下代码:

    a = b + 1
    /* do something with a */

在代码中的“do something”点,我们可以高度自信地声明a大于b。(是的,我忽略了未捕获整数溢出的可能性。我们不要拘泥于一个简单的例子。)

另一方面,如果代码是这样读的:

    ...
    goto 10
    ...
    a = b + 1
    10: /* do something with a */
    ...
    goto 10
    ...

标记10的方法的多样性意味着我们必须更加努力才能确信a和b在这一点上的关系。(事实上,在一般情况下,这是不可判断的!)

关于第4点,代码中“去某个地方”的整个概念只是一个比喻。除了电子和光子(用于余热),CPU内部没有任何东西真正“去”到任何地方。有时候,我们会放弃一个比喻,转而使用另一个更有用的比喻。我记得(几十年前!)遇到过一种语言

    if (some condition) {
      action-1
    } else {
      action-2
    }

通过将action-1和action-2编译为行外无参数例程,然后使用单个双参数VM操作码(使用条件的布尔值来调用其中一个)在虚拟机上实现。这个概念只是“选择现在调用什么”,而不是“去这里或去那里”。再一次,换一个比喻。

Using a goto makes it far too easy to write "spaghetti code" which is not particularly maintainable. The most important rule to follow is to write readable code, but of course it depends on what the goals of the project are. As a "best practice" avoiding a goto is a good idea. It's something extreme programming types would refer to as "code smell" because it indicates that you may be doing something wrong. Using a break while looping is remarkably similar to a goto, except it isn't a goto, but again is an indication that the code may not be optimal. This is why, I believe, it is also important to not find more modern programming loopholes which are essentially a goto by a different name.

后藤认为他很有帮助。

我从1975年开始编程。对于20世纪70年代的程序员来说,“goto被认为是有害的”这个词或多或少地表明,具有现代控制结构的新编程语言值得一试。我们确实尝试了新的语言。我们很快就皈依了。我们再也没有回去过。

我们再也没有回去过,但是,如果你更年轻,那么你就从来没有去过那里。

现在,拥有古老编程语言的背景可能并没有太大用处,除非它能显示程序员的年龄。尽管如此,年轻的程序员缺乏这方面的背景,所以他们不再理解口号“goto被认为是有害的”在引入时向目标受众传达的信息。

一个人不理解的口号是不太有启发性的。也许最好忘记这些口号。这样的口号无济于事。

然而,这个特别的口号,“后藤有害”,已经有了它自己的不死生命。

能去不被虐待吗?回答:当然,但那又怎样?实际上,每一个编程元素都可能被滥用。例如,普通bool被滥用的次数比我们中的一些人愿意相信的要多。

相比之下,自1990年以来,我不记得遇到过一次真正的goto滥用案例。

goto最大的问题可能不是技术问题,而是社交问题。不太懂的程序员有时似乎觉得不赞成goto会让他们听起来很聪明。您可能需要不时地满足这样的程序员。生活就是这样。

今天goto最糟糕的事情是它没有被充分使用。

直到C和c++(以及其他罪魁祸首)标记了断点和继续,goto将继续发挥作用。