问题
When do we use loop and a half? Also, should someone briefly elaborate how to write its code?
回答1:
You use loop-and-a-half to avoid repeating code from outside the loop to the inside. Example:
read a;
while a != b do
stuff;
read a;
end
becomes
while true do
read a
if a == b then break
stuff;
end
Now I only have the read in one place.
回答2:
As an aside, I'd like to add that the scope of the variable (assuming a
is a local variable in this idiom) is minimized as compared to the alternative case, where a
is still in scope even after the while loop terminates. Minimizing the scope of local variables is considered good practice whenever possible (Josh Bloch, Effective Java, Item 45).
来源:https://stackoverflow.com/questions/10767927/loop-and-a-half-controlled