Exiting multiple loop constructs
We've talked about labeled loops and a bit about existing loop constructs,
exiting loops, etc... but I do not think we came to any conclusive decision. Here
is a summary of different methods of exiting multiple loops:
integer in_top
in_top = 1
while in_top do
for i = 1 to 10 do
if i = 3 then
in_top = 0
exit
end if
end for
end while
This will work fine unless you have processing *under* the nested loop, then you
must provide an extra condition check (which is in a loop and is executed each
iteration):
integer in_top
in_top = 1
while in_top do
for i = 1 to 10 do
if i = 3 then
in_top = 0
exit
end if
end for
if in_top = 0 then
exit
end if
-- do more processing here
end while
NOTE: The above two methods compound in complexity with each nested loop you
add. However, in real life, I'm not sure if I have ever programmed a loop that is
3 deep.
This method uses optional numeric methods to exit and continue keywords:
while 1 do
for i = 1 to 10 do
if i = 3 then exit 2 -- end if
end for
end while
Notice "exit 2". That means exit 2 loops.
The final method is labeled loops, in which I will make a slightly more advanced
example.
while 1 label top do
for i = 1 to 10 label mid do
for j = 1 to 10 label bottom do
-- exit current loop "to" the top loop
if j = 2 then exit top end if
-- exit all loops (in this function)
if j = 5 then exit all end if
end for
end for
end while
So. Is one clearer than another? I do not know. Should any syntax change to
support exiting multiple loops? I am not sure, the benefit is you can remove
multiple checks making code easier to write and better performing.
So, what do you think? Are there other ways that I missed? What should be done?
--
Jeremy Cowgar
http://jeremy.cowgar.com
|
Not Categorized, Please Help
|
|