-
Is it really so bad?
[Originally posted by KilltheSand]
I'm converting some code into Visual Basic and I read that it was a terrible horrible thing if you modify the conditional variable of a for loop from within the loop.ÿ Is this true?ÿ I have an if within the loop and if it's true I do stuff, then I want to start the loop over.ÿ I would normally just set the variable back to zero before the end if.ÿ Is there any problem with this?ÿ As long as it's not true ever through the whole pass, the loop will terminate.ÿ I have some stuff to do after the loop so I don't want to use any recursion.ÿ Thank you for your comments.
Steve O.
-
Re:Is it really so bad?
[Originally posted by Greg DeBacker]
I'm not sure if it will cause real problems in your program but it is bad programming. Some one would really have to think about how this affects the stack and I'm too tired to do that right now. It would be best to put the For...Next loop in a Do...Loop.
Do Until bExitOK
ÿ ÿ For k = 1 to 100
ÿ ÿ ÿ ÿ If Something(k) = 74 Then
ÿ ÿ ÿ ÿ ÿ ÿ Exit For
ÿ ÿ ÿ ÿ Else
ÿ ÿ ÿ ÿ ÿ ÿ bExitOk
ÿ ÿ ÿ ÿ ÿ ÿ Exit For
ÿ ÿ ÿ ÿ End If
ÿ ÿ Next
Loop
Greg
-
Re:Is it really so bad?
[Originally posted by FreeVBCode.com]
In general it is not good practice but these types of things are only guidelines, not commandments.ÿ No need to be so dogmatic about it in my opinion.ÿ
-
Re:Is it really so bad?
[Originally posted by Chris Carta]
Yes, It's a very bad habit because it DOESN'T work.
Maybe I'm being picky, but you mentioned a 'FOR LOOP'.
In VB, that means only one thing.ÿ A block of code beginning with the key word FOR.
The following will NOT exit the for/loop when endIdx = 7 as you might expect.ÿ Try it.
ÿ ÿ Dim begIdx As Integer
ÿ ÿ Dim endIdx As Integer
ÿ ÿ
ÿ ÿ endIdx = 10
ÿ ÿ
ÿ ÿ For begIdx = 0 To endIdx
ÿ ÿ ÿ ÿ If begIdx = 5 Then
ÿ ÿ ÿ ÿ ÿ ÿ endIdx = 7
ÿ ÿ ÿ ÿ End If
ÿ ÿ Next begIdx
ÿ ÿ
ÿ ÿ MsgBox "Last index iterated was " & begIdx - 1
Instead, it loops until endIdx = 10, it's initial value which was set before the for/loop began.ÿ Setting endIdx within the loop doesn't do a thing to the for/loop once it is started.
I hope this helps explain what the author of what you read was referring to.
Chris
-
Re:Is it really so bad?
[Originally posted by KilltheSand]
Thanks for your help.ÿ Actually, I was changing the counting variable and not the destination variable but it is good to know the destination cannot be changed.ÿ Well, my function works fine (and I'm lazy) so I'm gonna leave it as is for now.ÿ Once I get my program finished I'll go back to optimize some code and find out if I'd rather modify variables or run two differant loops.
Steve O.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center
|