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条回答
我命由我不由天
2楼-- · 2019-01-20 09:06

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

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

查看更多
该账号已被封号
3楼-- · 2019-01-20 09:18

Following your logic here is the case when b would not be defined prior to first usage:

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

Note that very often boolean flags are a code small, try to avoid them rather than fight with them.

查看更多
Root(大扎)
4楼-- · 2019-01-20 09:18

You can write something like this if you want exit do-while block while boolean defined inside of do-while block.

do{
  boolean b;
  ...
  if(b){
    break;
  }
}while(otherCondition)  //or while(true)
查看更多
Luminary・发光体
5楼-- · 2019-01-20 09:20
public class DoWhileLoopExample {

    public static void main(String[] args) {

        int i=1;
        do {
            System.out.println("Do While Loop Example");

        } while(i<1);
    }
}
查看更多
叼着烟拽天下
6楼-- · 2019-01-20 09:21

In your example, the boolean variable b is scoped to the body of the do..while loop. Since the conditional check is executed outside the body, the variable is out of scope. The correct construct would be:

boolean b = false ; // Or whichever initial value you want
do {
    b = false;
} while (b);
查看更多
We Are One
7楼-- · 2019-01-20 09:22

It is basic scope rules. Variables declared inside a set of curly braces {} go out of scope at the end of the braces. It defeats the standard scope rules and it would be extra work for the compiler to detect such a case.

查看更多
登录 后发表回答