Scope of do-while loop?

2019-01-20 08:26发布

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.

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.

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 scope
8条回答
可以哭但决不认输i
2楼-- · 2019-01-20 09:24
do {
    boolean b = false;
}
while (b);

Because the boolean variable b is a local variable having scope only within a block.

From the JLS:

Every local variable declaration statement is immediately contained by a block.

查看更多
虎瘦雄心在
3楼-- · 2019-01-20 09:28

The statement definition and your variable are not visible outside your statement block {}, which is why the compiler complains.

The difference between the while and do ... while is that the do ... while is guaranteed to execute at least once and that is a more simpler way to write according to the JLS

Regarding scope of a variable, it has to be visible, according to these rules or else you get a compile time error.

查看更多
登录 后发表回答