每个人都知道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。

计算现代C程序中goto的数量。现在添加break、continue和return语句的数量。此外,加上你使用if、else、while、switch或case的次数。这是1968年Dijkstra写这封信时,如果你用FORTRAN或BASIC语言编写程序,你的程序会有多少个goto。

当时的编程语言缺乏控制流程。例如,在最初的达特茅斯BASIC中:

IF statements had no ELSE. If you wanted one, you had to write: 100 IF NOT condition THEN GOTO 200 ...stuff to do if condition is true... 190 GOTO 300 200 REM else ...stuff to do if condition is false... 300 REM end if Even if your IF statement didn't need an ELSE, it was still limited to a single line, which usually consisted of a GOTO. There was no DO...LOOP statement. For non-FOR loops, you had to end the loop with an explicit GOTO or IF...GOTO back to the beginning. There was no SELECT CASE. You had to use ON...GOTO.

因此,您的程序中最终出现了许多goto。并且您不能依赖于goto限制在单个子例程中(因为GOSUB…RETURN是一个非常弱的子例程概念),所以这些goto可以去任何地方。显然,这使得控制流难以遵循。

这就是反goto运动的由来。

其他回答

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

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操作码(使用条件的布尔值来调用其中一个)在虚拟机上实现。这个概念只是“选择现在调用什么”,而不是“去这里或去那里”。再一次,换一个比喻。

c++包含构造函数和析构函数。这允许一种称为RAII(资源分配是初始化)的模式。基本上,您创建一个本地堆栈变量,创建堆栈变量的行为打开一个文件,分配内存,锁定一个互斥锁,或以其他方式获取一个稍后必须释放的资源。

当变量超出作用域时,析构函数将运行并释放资源。

C语言没有这个特性。但您仍然经常需要在函数开始时获取资源,并在结束时释放它们。

你的函数可能有一个或多个错误条件导致它提前返回。您不希望重复资源释放代码。解决方案是使用goto。

例子:

int
foo(const char *arg)
{
    char *argcopy = strdup(arg);

    if (!isvalid(argcopy))
        goto out1;

    FILE *myfile = fopen(argcopy, "r");
    if (myfile == NULL)
      goto out1;

    char bytes[10];
    if (fread(bytes, sizeof(bytes), 1, myfile) != sizeof(mybytes))
        goto out2;

    /* do some actual work */
    /* .... */
    /* end of actual work */

    out2:
    fclose(myfile);

    out1:
    free(argcopy);

    return 0;
 }

拒绝程序员使用GOTO语句就像告诉木匠不要使用锤子,因为锤子在钉钉子的时候可能会损坏墙壁。真正的程序员知道如何以及何时使用GOTO。我跟随了一些所谓的“结构化程序”,我看到过这样可怕的代码,只是为了避免使用GOTO,我可以射杀程序员。好吧,为另一方辩护,我也见过一些真正的意大利面条代码,同样,那些程序员也应该被枪毙。

下面是我找到的一个小代码示例。

  YORN = ''
  LOOP
  UNTIL YORN = 'Y' OR YORN = 'N' DO
     CRT 'Is this correct? (Y/N) : ':
     INPUT YORN
  REPEAT
  IF YORN = 'N' THEN
     CRT 'Aborted!'
     STOP
  END

----------------------- 或 ----------------------

10:  CRT 'Is this Correct (Y)es/(N)o ':

     INPUT YORN

     IF YORN='N' THEN
        CRT 'Aborted!'
        STOP
     ENDIF
     IF YORN<>'Y' THEN GOTO 10

Donald E. Knuth在1992年CSLI出版的《识字编程》一书中回答了这个问题。在第17页有一篇文章“使用goto语句的结构化编程”(PDF)。我认为这篇文章也可能发表在其他书中。

本文描述了Dijkstra的建议,并描述了这种建议有效的情况。但他也给出了一些反例(问题和算法),这些反例仅用结构化循环是无法轻易重现的。

这篇文章包含了对问题、历史、例子和反例的完整描述。

在Linux:在Kernel Trap的内核代码中使用goto,有一个与Linus Torvalds和一个“新人”关于在Linux代码中使用goto的讨论。有一些非常好的观点,莱纳斯穿着平常的傲慢:)

一些段落:

莱纳斯:不,你被洗脑了 国安局的人认为尼克劳斯 Wirth其实知道自己是什么 说什么。他没有。他不 我有个该死的线索。”

-

莱纳斯:“我觉得goto很好,而且 它们通常比 大量的压痕。”

-

莱纳斯:“当然,用愚蠢的语言 就像帕斯卡,在那里标签不能 描述性的,后去可能很糟糕。”