loop and a half controlled [closed]

懵懂的女人 提交于 2019-11-30 14:03:56

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

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