do-while循环的范围? [英] Scope of do-while loop?
问题描述
在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
但这段代码对我有用。
此外,如果身体和状况在同一范围内,我找不到任何陷阱;因为正文总是被执行,而Java没有转到
,我不知道最外面的中的变量声明怎么做 - 而
可以跳过正文范围。即使有可能,编译器也总能检测到这种可能性,然后产生编译时错误。
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.
这种行为是否有任何原因(除了保留<$ c) $ c> do-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 how 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屋!