Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

java - Scope of do-while loop?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...