When do we use loop and a half? Also, should someone briefly elaborate how to write its code?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With