loop and a half controlled [closed]

女生的网名这么多〃 提交于 2019-11-29 20:21:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!