Re: Exit Do
- From: "mayayana" <mayaXXyana1a@xxxxxxxxxxxxxxxx>
- Date: Sat, 22 Mar 2008 09:34:38 -0400
I can't imagine what that person was thinking.
Exit Do is a good way to make a loop more efficient
when you don't need it anymore. The same goes
for Exit For. And it often makes sense to use
more than one Exit Do in a loop. That applies to VB
and VBScript. I wouldn't expect .Net to be different,
but I don't know anything about .Net.
----------------
s = "abcdefghijk"
i = 1
L = len(s)
Do while i <= L
s2 = mid(s, i, 1)
if s2 = "g" then exit do
i = i + 1
Loop
msgbox i
-----------------
That code will show a msgbox with "7".
You could also have skipped the contingent
While code and put that into the loop:
i = i + 1
If i > L then Exit Do
Loop
I prefer the second method because it keeps
all the business of the loop in the loop, so
I find it easier to read. But the first version
is probably a miniscule fraction faster.
You do need to watch out for the quirky behavior
of Do and For, though. Notice that the code above
shows 7. It doesn't exit the loop when you call
Exit Do. It exits at the end of the loop, which is
counterintuitive.
For / Next is even worse:
s = "abc"
For i = 1 to Len(s)
'--whatever
Next
MsgBox i
That code should show a msgbox with "3", since
3 was the last value for i, but it adds 1 to i when
it exits the loop, showing a result of "4"! That can be
slightly handy for checking whether a loop finished:
s = "ab"
For i = 1 to Len(s)
If mid(s, i, 1) = "b" Then Exit For
Next
MsgBox i
i will return 2 here. But if "b" were
not in the string then i would return 3. It kind of
makes sense as a way to design the For / Next loop,
but I find it so confusing, and so misleading when
one goes back later to read the code, that I prefer
to design things so that I'm not depending on the
value of i at all. Some people will think that's silly,
but those little issues are far less important than
being able to easily read your own code next month,
after you've forgotten it.
I've been instructed by a dot net / asp programmer that Exit Do is not a
great way to end a loop.
Can someone explain to me if this is so, or does this only apply to higher
level programming languages ?
I am using nested loops and need to exit out of one loop into another for
something to apply. Any other functional ways of doing this ?
Cheers,
.
- References:
- Exit Do
- From: Robbie Flower
- Exit Do
- Prev by Date: Re: InputBox output detection
- Next by Date: Re: Exit Do
- Previous by thread: Re: Exit Do
- Next by thread: Re: Exit Do
- Index(es):
Relevant Pages
|