I had an interesting discussion with my boss today regarding exiting a loop before the terminal condition is met. He had a construct in some of his VB6 code that looked something like this:
Dim Termination As Int
Termination = 10
For Iterator1 = 1 To Termination
If Iterator1 = 5 Then
Iterator1 = Termination
End If
Next
I questioned this implementation, contending that an Exit For
was the proper way to exit a loop prematurely based on a condition, like this:
For Iterator2 = 1 To 10
If Iterator2 = 5 Then
Exit For
End If
Next
I noted that in practice these probably both evaluate to the same machine language JMP opcode. My boss asserted that his implementation may be more efficient since it would have only one JMP, the one at the end of the loop, instead of two, one at the end and one in the middle for the Exit For
statement.
I prefer the second implementation for readability and semantics. Also, in the latest versions of Visual Studio for .Net if you add lines after the Exit For
statement you'll be warned that there are unreachable lines in your code. However, you don't get this warning in VB6, which is where the debate started.
So what's the best practice here? Is the first example better in VB6 or is the second example better in all situations? What are the advantages / disadvantages of each approach.
Edit: Removed magic number from code example to enhance question clarity.
Exit For
?