Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop and a half controlled [closed]

When do we use loop and a half? Also, should someone briefly elaborate how to write its code?

like image 300
aablah Avatar asked May 26 '12 16:05

aablah


2 Answers

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.

like image 69
stark Avatar answered Sep 24 '22 13:09

stark


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).

like image 40
Dhruv Gairola Avatar answered Sep 22 '22 13:09

Dhruv Gairola