do-while 循环的范围? [英] Scope of do-while loop?

查看:32
本文介绍了do-while 循环的范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,do-while 循环的主体和循环条件不属于同一范围.所以下面的代码不会编译:

In Java, the body of a do-while loop and the loop condition do not belong to the same scope. So the following code won't compile:

do {
    boolean b = false;
} while (b); // b cannot be resolved to a variable

但这段代码对我来说确实有意义.

But this code does make sense to me.

另外,如果body和condition在同一个范围内,我也找不到任何陷阱;由于主体总是会被执行,而 Java 没有 Goto,我不知道如何跳过最外层 do-while 主体范围中的变量声明.即使有可能,编译器也总能检测到这种可能性,然后产生编译时错误.

Also, I cannot find any pitfalls if the body and the condition are in the same scope; since the body will always get executed, and Java does not have Goto, I don't know how a variable declaration in the outermost do-while body scope could be skipped. Even if it is possible, the compiler could always detect such possibility and then produce compile time errors.

这种行为是否有任何原因(除了将 do-while 循环保持为与 while 相同的格式)?我真的很好奇.感谢您的任何投入!

Is there any reason for this behavior (aside from keeping the do-while loop in the same format as while)? I am really curious. Thanks for any inputs!

推荐答案

因为这是 Java 中定义作用域的一种方式;{} 里面是一个新的作用域.

Because that's one way scope is defined in Java; inside {} is a new scope.

IMO 对单个构造进行特殊处理没有多大意义.

IMO it wouldn't make much sense to special-case a single construct.

这篇关于do-while 循环的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆