Scope of the Java – do while loop?

In Java, the body of a do - while loop and the loop condition do not belong to the same scope Therefore, the following code will not be compiled:

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

But this code makes sense to me

In addition, if my body and condition are in the same range, I can't find any traps; Because the body is always executed and Java doesn't have goto, I don't know how to skip the variable declaration in the outermost do while body range Even if possible, the compiler can always detect this possibility and generate compile time errors

Is there any reason for this behavior (except to keep the do while loop in the same format as while)? I'm curious. Thank you for any input!

Solution

Because this is the scope defined in Java; Inside {} is a new scope

In special circumstances, a single structure of IMO will not make any sense

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>