Alex Rivera | Logout

Scope of do-while loop?

Asked 2011-11-09T17:13:18.357
14

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!

Edit
Report

1 Answer

2

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)
answered 2011-11-09T17:26:47.403

Your Answer