1. Home
  2. Computing & Technology
  3. Visual Basic

Chapter 7 - Using Loops and Timers - Part 2

By Dan Mabbutt, About.com

2 of 4

Beyond The Book: Infinite Loops - A Code Writing Challenge!)

Get a free book - Code a clever infinite loop

The book has a just a few brief comments about infinite loops (called Endless Loops in the Book) on page 197, (and the clever example we used earlier) but the subject deserves a lot more attention. They can be tricky and subtle, especially when the program statements inside the loop change the value that determines when the loop ends.

Consider this simple code:

~~~~~~~~~~~~~~~~~~~~~~~~~
Dim MyNumber As Integer
For MyNumber = 1 To 10
  MyNumber -= 1
Next MyNumber
~~~~~~~~~~~~~~~~~~~~~~~~~

If you run this code, your computer will slow to a near stop because the program enters a very tight infinite loop. This one is easy to see, but what if the For ... Next loop was spread over about ten pages of code and MyNumber was changed in a lot of statements sprinkled throughout the ten pages? It might be a lot harder to figure out! So ... be very careful about this. It's easier to make a mistake here than you might think!

The key information that the book leaves outis what to do if you happen to code one of these little nasties by mistake. Your program is looping out of control and doing anything takes a long time.

Explore Visual Basic
By Category
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Visual Basic
  4. Learn VB.NET
  5. Using Loops and Timers - Part 2

©2009 About.com, a part of The New York Times Company.

All rights reserved.