我对此感到困惑。我们大多数人都听说过Java中没有goto语句。

但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?


当前回答

请注意,您可以将goto的大多数良性用途替换为by

返回 打破 打破标签 扔进去,试着抓住,最后

其他回答

我也不喜欢goto,因为它通常会降低代码的可读性。然而,我相信这条规则也有例外(特别是涉及词法分析器和解析器时!)

当然,你也可以把程序转换成类似于汇编程序的形式,然后编写类似于

int line = 1;
boolean running = true;
while(running)
{
    switch(line++)
    {
        case 1: /* line 1 */
                break;
        case 2: /* line 2 */
                break;
        ...
        case 42: line = 1337; // goto 1337
                break;
        ...
        default: running = false;
                break;
    }
}

(所以你基本上写了一个执行二进制代码的虚拟机…其中line对应于指令指针)

这比使用goto的代码可读性强多了,不是吗?

因此,如果语言设计者觉得有必要的话,它们是可以被使用的。

此外,如果来自具有这些关键字的语言的程序员(例如。C, c++)错误地使用它们,那么Java编译器可以给出有用的错误消息。

或者只是为了阻止程序员使用goto:)

它们被保留以供将来使用(请参阅:Java语言关键字)

关键字const和goto是保留的,即使它们目前没有被使用。

Java中没有goto语句的原因可以在“Java语言环境”中找到:

Java has no goto statement. Studies illustrated that goto is (mis)used more often than not simply "because it's there". Eliminating goto led to a simplification of the language--there are no rules about the effects of a goto into the middle of a for statement, for example. Studies on approximately 100,000 lines of C code determined that roughly 90 percent of the goto statements were used purely to obtain the effect of breaking out of nested loops. As mentioned above, multi-level break and continue remove most of the need for goto statements.

http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.goto

如果有人告诉你Java中没有goto语句,那你就被骗了。事实上,Java由两层“源代码”组成。

当然,它是关键字,但它不在源代码级别上使用。

但如果使用jasmin或其他转换为字节码的低级语言,那么“goto”就在那里