Reputation: 27200
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!
Upvotes: 14
Views: 6893
Reputation: 340743
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 smell, try to avoid them rather than fight with them.
Upvotes: 16
Reputation: 160191
Because that's one way scope is defined in Java; inside {}
is a new scope.
IMO it wouldn't make much sense to special-case a single construct.
Upvotes: 10
Reputation: 69
public class DoWhileLoopExample {
public static void main(String[] args) {
int i=1;
do {
System.out.println("Do While Loop Example");
} while(i<1);
}
}
Upvotes: 0
Reputation: 2635
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.
Upvotes: 0
Reputation: 1043
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)
Upvotes: 2
Reputation: 7078
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.
Upvotes: 1
Reputation: 6366
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.
Upvotes: 0
Reputation: 2115
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);
Upvotes: 2