Scope of do-while loop?

2019-01-20 08:28发布

问题:

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!

回答1:

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.



回答2:

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.



回答3:

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);


回答4:

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.



回答5:

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.



回答6:

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)


回答7:

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.



回答8:

public class DoWhileLoopExample {

    public static void main(String[] args) {

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

        } while(i<1);
    }
}


标签: java scope